pluv.io is in preview! Please wait for a v1.0.0 stable release before using this in production.

Loading Storage

Listen to when a room is deleted so that when the same room is re-created, users can resume from the same storage as where they left off.

Add listeners

1// server/io.ts
2
3import { yjs } from "@pluv/crdt-yjs";
4import { createIO } from "@pluv/io";
5import { platformNode } from "@pluv/platform-node";
6import { db } from "./db";
7
8export const io = createIO({
9 // Specify which CRDT to use here
10 crdt: yjs,
11 // Load storage for a newly created room.
12 getInitialStorage: async ({ room }) => {
13 const existingRoom = await db.room.findUnique({ where: { room } });
14
15 return existingRoom?.encodedState ?? null;
16 },
17 platform: platformNode(),
18 // Before the room is destroyed, persist the state to a database
19 // to load when the room is re-created.
20 onRoomDeleted: async ({ encodedState, room }) => {
21 await db.room.upsert({
22 where: { room },
23 create: { encodedState, room },
24 update: { encodedState },
25 });
26 },
27 // It is unnecessary to save the storage state in this listener.
28 // If a room already exists, users will load the currently active
29 // storage before the storage from initialStorage.
30 onStorageUpdated: ({ encodedState, room }) => {
31 console.log(room, encodedState);
32 },
33});