PlayerData: increment() method

Available since @irtio/room 0.1Hosted roomsirt dev@irtio/testingSelf-hosted room host

The increment() method of the PlayerData interface adds to a number in one step, creating the key at 0 when it has no value, and resolves with the new number.

Syntax

increment(key)
increment(key, by)
increment(key, by, options)

Parameters

key
The key, 1 to 64 of A-Z a-z 0-9 _ . : -.
by Optional
The number to add. Defaults to 1.
options Optional

An object with this property:

once
A key that makes the write safe to repeat, as for set(). A repeat resolves with the number the first write made, which may have changed since.

Return value

A Promise that resolves with the key’s new number.

Exceptions

The promise rejects with a DataError, such as E_TYPE when the key holds a value that isn’t a number.

Description

increment() adds in one step, with no get() first, so it suits counters such as coins or games played. It takes no version.

Examples

Paying out a match once

The match ID is in room state, so a room that repeats the payout after a wake adds nothing.

// payout.ts
import { defineRoom, defineSchema, entity } from "@irtio/room";

const Match = entity("match", { matchId: "string", winner: "string" });

export default defineRoom({
  schema: defineSchema({ state: Match }),
  onCreate(room) {
    room.state.matchId = room.id;
  },
  async onMessage(room, connection, message) {
    if (message !== "i-won" || room.state.winner !== "") return;
    room.state.winner = connection.player;
    const coins = await room.playerData(connection.player).increment("coins", 25, { once: `win:${room.state.matchId}` });
    room.send(connection, { type: "coins", coins });
  },
});

See also

Runtime availability

Hosted roomsirt dev@irtio/testingSelf-hosted room host
increment()0.10.10.10.1