UNPKG

partysync

Version:

Experimental library to synchronize state between a Durable Object and client. See [design discussion](https://github.com/cloudflare/partykit/issues/147).

64 lines (62 loc) 1.62 kB
import { Server } from "partyserver"; //#region src/server/index.ts var SyncServer = class extends Server { static options = { hibernate: true }; onAction(channel, action) { throw new Error("onAction not implemented, you should implement this in your server"); } async onMessage(connection, message) { if (typeof message !== "string") { console.error("Received non-string message"); return; } let json; try { json = JSON.parse(message); } catch (err) { connection.send(JSON.stringify({ type: "exception", rpc: true, exception: [`Failed to parse message: ${err.message}`] })); return; } const channel = json.channel; if ("sync" in json && json.sync) { connection.send(JSON.stringify({ sync: true, channel, payload: [...json.from ? this.ctx.storage.sql.exec(`SELECT * FROM ${channel} WHERE deleted_at IS NULL AND updated_at > ?`, json.from).raw() : this.ctx.storage.sql.exec(`SELECT * FROM ${channel} WHERE deleted_at IS NULL`).raw()] })); return; } const { id: messageId, action } = json; try { const result = await this.onAction(channel, action); connection.send(JSON.stringify({ type: "success", rpc: true, channel, id: messageId, result })); this.broadcast(JSON.stringify({ broadcast: true, type: "update", channel, payload: result }), [connection.id]); } catch (err) { connection.send(JSON.stringify({ type: "error", rpc: true, channel, id: messageId, error: [err.message] })); } } }; //#endregion export { SyncServer }; //# sourceMappingURL=index.js.map