DataClient: collection() method
Available since
@irtio/client 5.0BrowsersNodeThe 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. WithclientRead: "own", it gets and lists only the entries it owns: aget()of another player’s entry resolves withundefined, and alist()with anotherownerrejects withE_FORBIDDEN. WithoutclientRead, reads reject withE_FORBIDDEN. - Writing. With
clientWrite: "own", the client creates entries and changes and deletes its own.owneris always the client’s player, whatever it sends, andmaxOwncaps how many it creates: past it, a create rejects withE_QUOTA. Writes can’t useonce, which rejects withE_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
CollectionRoomClient.collection(), the same from a connected client- Player data, collections and leaderboards
Runtime availability
| Browsers | Node | |
|---|---|---|
collection() | 5.0 | 5.0 |