74 lines
2.6 KiB
TypeScript
74 lines
2.6 KiB
TypeScript
/**
|
|
* Maps the rows of `chat_messages` to the {@link ChatMessage} the API sends.
|
|
* Only `services/chat-service.ts` uses it, on the rows of its one query.
|
|
*
|
|
* @module
|
|
*/
|
|
|
|
import type { SQLOutputValue } from "node:sqlite";
|
|
import type { ChatMessage } from "../../shared/chat.ts";
|
|
|
|
/**
|
|
* Returned by chat-service's query, which joins each message to its author and
|
|
* to the message it replies to. `reply_to_id` is kept when the message it
|
|
* points to is deleted, while `reply_to_author` and `reply_to_body` then read
|
|
* null.
|
|
*/
|
|
export interface ChatMessageRow {
|
|
id: string;
|
|
user_id: string;
|
|
body: string;
|
|
created_at: string;
|
|
updated_at: string | null;
|
|
author_username: string;
|
|
author_avatar_mime: string | null;
|
|
reply_to_id: string | null;
|
|
reply_to_author: string | null;
|
|
/** Cut to chat-service's `REPLY_SNIPPET_LEN` characters. */
|
|
reply_to_body: string | null;
|
|
[key: string]: SQLOutputValue;
|
|
}
|
|
|
|
/**
|
|
* Checks whether `obj`, a row read by chat-service, is a
|
|
* {@link ChatMessageRow}.
|
|
*/
|
|
export function isChatMessageRow(obj: unknown): obj is ChatMessageRow {
|
|
return !!obj && typeof obj === "object" &&
|
|
"id" in obj && typeof obj.id === "string" &&
|
|
"user_id" in obj && typeof obj.user_id === "string" &&
|
|
"body" in obj && typeof obj.body === "string" &&
|
|
"created_at" in obj && typeof obj.created_at === "string" &&
|
|
"updated_at" in obj &&
|
|
(typeof obj.updated_at === "string" || obj.updated_at === null) &&
|
|
"author_username" in obj && typeof obj.author_username === "string" &&
|
|
"author_avatar_mime" in obj &&
|
|
(typeof obj.author_avatar_mime === "string" ||
|
|
obj.author_avatar_mime === null) &&
|
|
"reply_to_id" in obj &&
|
|
(typeof obj.reply_to_id === "string" || obj.reply_to_id === null) &&
|
|
"reply_to_author" in obj &&
|
|
(typeof obj.reply_to_author === "string" || obj.reply_to_author === null) &&
|
|
"reply_to_body" in obj &&
|
|
(typeof obj.reply_to_body === "string" || obj.reply_to_body === null);
|
|
}
|
|
|
|
/**
|
|
* Converts a row to the {@link ChatMessage} that chat-service returns, turning
|
|
* its timestamps into Dates and its nulls into absent fields.
|
|
*/
|
|
export function chatMessageRowToApi(row: ChatMessageRow): ChatMessage {
|
|
return {
|
|
id: row.id,
|
|
userId: row.user_id,
|
|
body: row.body,
|
|
createdAt: new Date(row.created_at),
|
|
updatedAt: row.updated_at ? new Date(row.updated_at) : undefined,
|
|
authorUsername: row.author_username,
|
|
authorAvatarMime: row.author_avatar_mime ?? undefined,
|
|
replyToId: row.reply_to_id ?? undefined,
|
|
replyToAuthor: row.reply_to_author ?? undefined,
|
|
replyToBody: row.reply_to_body ?? undefined,
|
|
};
|
|
}
|