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
Tobias Berger 7746e3ebdd Message author as id instead of name
Also add optional MessageType as parameter for isServerMessage
2022-01-08 15:54:05 +01:00

65 lines
1.5 KiB
TypeScript

export enum MessageType {
ACK = 0,
TEXT = 1,
}
export type ServerMessage = {
type: MessageType;
date: number;
};
export function isServerMessage(
obj: unknown,
type?: MessageType
): obj is ServerMessage {
if (typeof obj !== "object") return false;
if (obj === null) return false;
if (
!Object.hasOwnProperty.call(obj, "type") ||
typeof (obj as { type: unknown }).type !== "number" ||
(type === undefined &&
!Object.hasOwnProperty.call(
MessageType,
(obj as { type: number }).type
)) ||
(type !== undefined && (obj as { type: number }).type !== type)
) {
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: number;
content: string;
};
export function isTextMessage(obj: unknown): obj is TextMessage {
if (!isServerMessage(obj, MessageType.TEXT)) return false;
if (
!Object.hasOwnProperty.call(obj, "author") ||
typeof (obj as ServerMessage & { author: unknown }).author !== "number"
) {
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 {
return isServerMessage(obj, MessageType.ACK);
}