Add CONNECTED_USERS MessageType

This commit is contained in:
Tobias Berger 2022-01-21 12:59:39 +01:00
parent cde3d62b1c
commit 26b7ffe0ff

View file

@ -4,6 +4,7 @@ export enum MessageType {
ID_RESPONSE = 3,
TYPING = 4,
CURRENTLY_TYPING = 5,
CONNECTED_USERS = 6,
}
export type ServerMessage = {
@ -110,15 +111,67 @@ export function isCurrentlyTypingMessage(
if (
!Object.hasOwnProperty.call(obj, "currently") ||
typeof obj !== "object" ||
!(
(obj as ServerMessage & { currently: unknown }).currently instanceof Array
) ||
Array.prototype.some.call(
!Array.isArray((obj as ServerMessage & { currently: unknown }).currently) ||
!Array.prototype.every.call(
(obj as ServerMessage & { currently: unknown[] }).currently,
(element) => typeof element !== "string"
(element) => typeof element === "string"
)
) {
return false;
}
return true;
}
export type ConnectedUser = {
id: string;
desiredName?: string;
};
export function isConnectedUser(obj: unknown): obj is ConnectedUser {
if (typeof obj !== "object" || obj === null) {
return false;
}
if (
!Object.prototype.hasOwnProperty.call(obj, "id") ||
typeof (obj as { id: unknown }).id !== "string"
) {
return false;
}
if (
Object.prototype.hasOwnProperty.call(obj, "desiredName") &&
typeof (obj as { desiredName: unknown }).desiredName !== "string"
) {
return false;
}
return true;
}
export type ConnectedUsersMessage = ServerMessage & {
type: MessageType.CONNECTED_USERS;
connected: ConnectedUser[];
};
export function isConnectedUsersMessage(
obj: unknown
): obj is ConnectedUsersMessage {
if (!isServerMessage(obj, MessageType.CONNECTED_USERS)) {
return false;
}
if (
typeof (obj as ServerMessage & { connected: unknown }).connected !==
"object" ||
!Array.isArray((obj as ServerMessage & { connected: unknown }).connected)
) {
return false;
}
if (
!Array.prototype.every.call(
(obj as ServerMessage & { connected: unknown[] }).connected,
(maybeUser) => isConnectedUser(maybeUser)
)
) {
return false;
}
return false;
}