json() function

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

The json() function declares a json field whose values have a type, for entity() or call().

Syntax

json<T>(initial)
json<T>()

Parameters

initial Optional
The value every new entity starts with, each with its own copy: JSON of at most 16 KB. It’s part of the schema hash. Without it, or with null, the field starts as null.

Return value

A field declaration. With an initial value, the field is typed T; without one, T | null. As a call arg, a json<T>() arg is typed T.

Exceptions

TypeError or RangeError
Thrown by entity() for an initial value that isn’t JSON or is over 16 KB, and by call() for a json arg with an initial value, since an arg is always sent.

Description

The type isn’t checked at runtime. A json<T>() declared without an initial value has the same schema hash as a plain "json" field.

Examples

A scoreboard every player sees

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

const Match = entity("match", { scores: json<Record<string, number>>({}), lastGoal: json<{ by: string; at: number }>() });

export default defineRoom({
  schema: defineSchema({ state: Match }),
  onMessage(room, connection, message) {
    if (message !== "goal") return;
    room.state.scores = { ...room.state.scores, [connection.player]: (room.state.scores[connection.player] ?? 0) + 1 };
    room.state.lastGoal = { by: connection.player, at: room.now() };
  },
});

See also

Runtime availability

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