decentralised message store
1import db from "@/db";
2import type { ShardMessageSelect } from "@/db/schema/messages";
3import { messagesTable, type ShardMessageInsert } from "@/db/schema/messages";
4import type { ShardMessage } from "@/lib/types/messages";
5import type { Result } from "@/lib/utils/result";
6import * as TID from "@atcute/tid";
7import { eq } from "drizzle-orm";
8
9export const storeMessageInDb = async (message: ShardMessage) => {
10 const tid = TID.now();
11 const {
12 content,
13 channel: channelAtUri,
14 sentBy: authorDid,
15 sentAt,
16 } = message;
17 const messageToStore: ShardMessageInsert = {
18 id: tid,
19 authorDid,
20 content,
21 channelAtUri,
22 sentAt,
23 createdAt: new Date(),
24 };
25
26 const insertResult = await db.insert(messagesTable).values(messageToStore);
27
28 if (insertResult.rowsAffected > 0) console.log("Stored!");
29 else {
30 console.error("Something went wrong storing", messageToStore);
31 console.error("insertResult:", insertResult);
32 }
33};
34
35export const getChannelHistory = async (
36 channelAtUriString: string,
37): Promise<Result<Array<ShardMessageSelect>, unknown>> => {
38 const messages = await db
39 .select()
40 .from(messagesTable)
41 .where(eq(messagesTable.channelAtUri, channelAtUriString))
42 .limit(100000);
43 return { ok: true, data: messages };
44};