Add type-safe message decoding
This commit is contained in:
parent
4c0f0fbf52
commit
05629a00a0
1 changed files with 25 additions and 1 deletions
|
|
@ -25,9 +25,33 @@ export function encode(msg: ServerMessage): string {
|
||||||
return JSON.stringify(msg);
|
return JSON.stringify(msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isClientMessage(obj: unknown): obj is ClientMessage {
|
||||||
|
if (typeof obj !== "object" || obj === null) return false;
|
||||||
|
const msg = obj as Record<string, unknown>;
|
||||||
|
|
||||||
|
switch (msg.type) {
|
||||||
|
case "join":
|
||||||
|
return typeof msg.room === "string";
|
||||||
|
case "leave":
|
||||||
|
return true;
|
||||||
|
case "update":
|
||||||
|
return (
|
||||||
|
Array.isArray(msg.data) && msg.data.every((n) => typeof n === "number")
|
||||||
|
);
|
||||||
|
case "awareness":
|
||||||
|
return (
|
||||||
|
Array.isArray(msg.data) && msg.data.every((n) => typeof n === "number")
|
||||||
|
);
|
||||||
|
default:
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function decode(raw: string): ClientMessage | null {
|
export function decode(raw: string): ClientMessage | null {
|
||||||
try {
|
try {
|
||||||
return JSON.parse(raw) as ClientMessage;
|
const parsed = JSON.parse(raw);
|
||||||
|
if (!isClientMessage(parsed)) return null;
|
||||||
|
return parsed;
|
||||||
} catch {
|
} catch {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue