PlayerData: set() method
Available since
@irtio/room 0.1Hosted roomsirt dev@irtio/testingSelf-hosted room hostThe set() method of the PlayerData interface writes a key’s value and resolves with its new version.
Syntax
set(key, value)
set(key, value, options)
Parameters
key- The key, 1 to 64 of
A-Z a-z 0-9 _ . : -. value- JSON, or a
Uint8Array, at most 64 KB.undefinedis stored asnull. optionsOptional-
An object with any of these properties:
version- The version the key must have, or the write fails with
E_VERSION.0means the key must have none. Without it, the write is unconditional. once- A key, 1 to 64 of
A-Z a-z 0-9 _ . : -, that makes the write safe to repeat: a write with aoncekey the project used in the last day doesn’t run again, and resolves as the first did. The same key with different arguments fails withE_INVALID.
Return value
A Promise that resolves with { version }, the key’s new version.
Exceptions
The promise rejects with a DataError whose code is, among others:
E_VERSION- The key doesn’t have the
versiongiven. E_QUOTA- The write would take the player over 256 keys or 1 MB.
E_INVALID- The key or value is malformed or over 64 KB, or
oncewas used with different arguments. E_UNAVAILABLE- The data service couldn’t be reached. The write may or may not have happened; repeat it with
versionoronce.
Examples
Saving progress only over what was loaded
// checkpoint.ts
import { DataError, defineRoom } from "@irtio/room";
export default defineRoom({
async onJoin(room, connection) {
const save = await room.playerData(connection.player).get<{ checkpoint: number }>("progress");
connection.data.checkpoint = save?.value.checkpoint ?? 0;
connection.data.version = save?.version ?? 0;
},
async onMessage(room, connection, message) {
if (message !== "checkpoint") return;
const progress = { checkpoint: connection.data.checkpoint + 1 };
try {
const { version } = await room.playerData(connection.player).set("progress", progress, { version: connection.data.version });
connection.data.checkpoint = progress.checkpoint;
connection.data.version = version;
} catch (e) {
if (e instanceof DataError && e.code === "E_VERSION") room.kick(connection, "your save changed elsewhere; rejoin");
else throw e;
}
},
});
See also
Runtime availability
| Hosted rooms | irt dev | @irtio/testing | Self-hosted room host | |
|---|---|---|---|---|
set() | 0.1 | 0.1 | 0.1 | 0.1 |