This repository has been archived on 2022-02-07. You can view files and clone it, but cannot push or open issues or pull requests.
web-drs-lib/types/ServerMessage.ts

61 lines
1.5 KiB
TypeScript
Raw Normal View History

2022-01-07 17:43:05 +01:00
export enum MessageType {
2022-01-07 18:28:34 +01:00
ACK = 0,
TEXT = 1,
2022-01-07 17:43:05 +01:00
}
export type ServerMessage = {
2022-01-07 18:28:34 +01:00
type: MessageType;
2022-01-07 17:43:05 +01:00
date: number;
};
export function isServerMessage(obj: unknown): obj is ServerMessage {
if (typeof obj !== "object") return false;
if (obj === null) return false;
if (
!Object.hasOwnProperty.call(obj, "type") ||
2022-01-07 18:28:34 +01:00
typeof (obj as { type: unknown }).type !== "number" ||
!Object.hasOwnProperty.call(MessageType, (obj as { type: number }).type)
2022-01-07 17:43:05 +01:00
) {
return false;
}
if (
!Object.hasOwnProperty.call(obj, "date") ||
typeof (obj as { date: unknown }).date !== "number"
) {
return false;
}
return true;
}
export type TextMessage = ServerMessage & {
type: MessageType.TEXT;
author: string;
content: string;
};
export function isTextMessage(obj: unknown): obj is TextMessage {
if (!isServerMessage(obj)) return false;
if (obj.type !== MessageType.TEXT) return false;
if (
!Object.hasOwnProperty.call(obj, "author") ||
typeof (obj as ServerMessage & { author: unknown }).author !== "string"
) {
return false;
}
if (
!Object.hasOwnProperty.call(obj, "author") ||
typeof (obj as ServerMessage & { content: unknown }).content !== "string"
) {
return false;
}
return true;
}
export type AckMessage = ServerMessage & {
type: MessageType.ACK;
};
export function isAckMessage(obj: unknown): obj is AckMessage {
if (!isServerMessage(obj)) return false;
if (obj.type !== MessageType.ACK) return false;
return true;
}