diff --git a/back/src/constants.ts b/back/src/constants.ts new file mode 100644 index 0000000..f207bf5 --- /dev/null +++ b/back/src/constants.ts @@ -0,0 +1 @@ +export const idMsgTypes = ["freed", "occupied"] as const; diff --git a/back/src/index.ts b/back/src/index.ts index 3da887c..1bed51b 100644 --- a/back/src/index.ts +++ b/back/src/index.ts @@ -1,6 +1,7 @@ import "reflect-metadata"; import { Server } from "ws"; import { connect, getRoomList } from "./db"; +import { isIdMessage, isMessage } from "./types"; (async () => { const connection = await connect(); @@ -11,5 +12,13 @@ import { connect, getRoomList } from "./db"; wss.on("connection", async (ws) => { ws.send(JSON.stringify(await getRoomList(connection))); + + ws.on("message", (data) => { + const message: unknown = JSON.parse(data.toString()); + if (!isMessage(message)) throw new Error("Message corrupted"); + + if (isIdMessage(message)) + updateFree(message.args.id, message.type === "freed"); + }); }); })(); diff --git a/back/src/types.ts b/back/src/types.ts new file mode 100644 index 0000000..78acf14 --- /dev/null +++ b/back/src/types.ts @@ -0,0 +1,32 @@ +import { idMsgTypes } from "./constants"; + +export type IdMsgTypes = typeof idMsgTypes[number]; + +export type Message = { + type: string; + args: unknown; +}; + +export type IdMessage = Message & { + type: IdMsgTypes; + args: { + id: number; + }; +}; + +const hasProperty = ( + obj: T, + prop: U +): obj is T & Record => prop in obj; + +export const isMessage = (obj: unknown): obj is Message => + typeof obj === "object" && + hasProperty(obj, "type") && + typeof obj.type === "string" && + hasProperty(obj, "args"); + +export const isIdMessage = (message: Message): message is IdMessage => + idMsgTypes.reduce((prev, curr) => prev || curr === message.type, false) && + typeof message.args === "object" && + hasProperty(message.args, "id") && + typeof message.args.id === "number";