Added basic message handling

This commit is contained in:
Dmitriy Shishkov 2021-09-04 15:45:26 +03:00
parent e95f74891f
commit 73b3ee0a10
No known key found for this signature in database
GPG Key ID: 14358F96FCDD8060
3 changed files with 42 additions and 0 deletions

1
back/src/constants.ts Normal file
View File

@ -0,0 +1 @@
export const idMsgTypes = ["freed", "occupied"] as const;

View File

@ -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");
});
});
})();

32
back/src/types.ts Normal file
View 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";