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