DataClient: collection() method

Available since @irtio/client 5.0BrowsersNode

The collection() method of the DataClient interface returns one of the project’s collections, declared under settings.data.collections in irt.config.ts.

Syntax

collection(name)

Parameters

name
A string: the collection’s name.

Return value

A Collection, with the Room API’s get(), put(), list(), delete() and refresh() methods.

Exceptions

None. Its calls reject with a DataError; E_UNKNOWN means the collection isn’t declared in the live build.

Description

A client’s calls follow the collection’s client settings:

  • Reading. With clientRead: true, the client gets and lists every entry. With clientRead: "own", it gets and lists only the entries it owns: a get() of another player’s entry resolves with undefined, and a list() with another owner rejects with E_FORBIDDEN. Without clientRead, reads reject with E_FORBIDDEN.
  • Writing. With clientWrite: "own", the client creates entries and changes and deletes its own. owner is always the client’s player, whatever it sends, and maxOwn caps how many it creates: past it, a create rejects with E_QUOTA. Writes can’t use once, which rejects with E_INVALID.

Nothing is cached on the client, so every get() reads from the router and refresh() has nothing to drop.

Examples

Sharing a level the player built

The level editor saves the player’s tiles as an entry they own, which needs the collection’s clientWrite: "own".

// share-level.ts
import { dataClient, DataError } from "@irtio/client";

const data = dataClient();

export async function shareLevel(name: string, tiles: number[]) {
  try {
    const { id } = await data.collection("levels").put({ value: { tiles }, meta: { name } });
    console.log(`shared as ${id}`);
    return id;
  } catch (e) {
    if (!(e instanceof DataError) || e.code !== "E_QUOTA") throw e;
    console.warn("delete a level to share another");
    return undefined;
  }
}

E_QUOTA here means the player reached the collection’s maxOwn.

See also

Runtime availability

BrowsersNode
collection()5.05.0