RoomClient: collection() method

Available since @irtio/client 5.0BrowsersNode

The collection() method of the RoomClient interface returns a Collection: one of the project’s collections of entries, declared under settings.data.collections in irt.config.ts, read and written as this player.

Syntax

collection(name)

Parameters

name
A string: the collection’s name, as irt.config.ts declares it.

Return value

A Collection, whose get(), put(), list() and delete() methods return promises. Getting it makes no request, and doesn’t check name: a collection that isn’t declared fails each call with E_UNKNOWN.

Exceptions

None.

Description

The collection’s calls go to the router over HTTP, with the connection’s token or guest, so they need no open connection to the room. They’re the same calls dataClient() makes. Nothing is cached on the client: every call goes to the router.

A client has the rights the collection’s settings give clients:

  • It reads entries with clientRead: true, or only its own with clientRead: "own". Then a get() of another player’s entry resolves with undefined, and a list() with another owner rejects with E_FORBIDDEN.
  • With clientWrite: "own", it creates entries and changes and deletes its own, up to the collection’s maxOwn entries.
  • An entry’s owner is always this player.
  • Its writes can’t use once.

Calls reject with DataError, which @irtio/client also exports: E_UNAVAILABLE when the router or the data service can’t be reached, E_LIMIT over the router’s 10 calls a second per address and per player, E_FORBIDDEN for what the settings don’t allow, E_QUOTA for a create past maxOwn and E_INVALID for a write with once.

Examples

Publishing a level

A level editor publishes the player’s level to a levels collection that lets clients create entries, and tells the player when the project doesn’t allow it.

// publish-level.ts
import { DataError, type ReadyRoomClient } from "@irtio/client";

export async function publishLevel(room: ReadyRoomClient, tiles: number[]): Promise<string | undefined> {
  try {
    const { id } = await room.collection("levels").put({ value: { tiles }, meta: { size: tiles.length } });
    return id;
  } catch (e) {
    if (e instanceof DataError && e.code === "E_FORBIDDEN") {
      console.warn("Publishing levels is turned off for this game.");
      return undefined;
    }
    throw e;
  }
}

See also

Runtime availability

BrowsersNode
collection()5.05.0