Added basic message handling
This commit is contained in:
parent
e95f74891f
commit
73b3ee0a10
1
back/src/constants.ts
Normal file
1
back/src/constants.ts
Normal file
@ -0,0 +1 @@
|
|||||||
|
export const idMsgTypes = ["freed", "occupied"] as const;
|
@ -1,6 +1,7 @@
|
|||||||
import "reflect-metadata";
|
import "reflect-metadata";
|
||||||
import { Server } from "ws";
|
import { Server } from "ws";
|
||||||
import { connect, getRoomList } from "./db";
|
import { connect, getRoomList } from "./db";
|
||||||
|
import { isIdMessage, isMessage } from "./types";
|
||||||
|
|
||||||
(async () => {
|
(async () => {
|
||||||
const connection = await connect();
|
const connection = await connect();
|
||||||
@ -11,5 +12,13 @@ import { connect, getRoomList } from "./db";
|
|||||||
|
|
||||||
wss.on("connection", async (ws) => {
|
wss.on("connection", async (ws) => {
|
||||||
ws.send(JSON.stringify(await getRoomList(connection)));
|
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");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
})();
|
})();
|
||||||
|
32
back/src/types.ts
Normal file
32
back/src/types.ts
Normal file
@ -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 = <T extends {}, U extends PropertyKey>(
|
||||||
|
obj: T,
|
||||||
|
prop: U
|
||||||
|
): obj is T & Record<U, unknown> => 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";
|
Loading…
x
Reference in New Issue
Block a user