Co-authored-by: Jason Woltje <jason@diversecanvas.com> Co-committed-by: Jason Woltje <jason@diversecanvas.com>
50 lines
1.7 KiB
TypeScript
50 lines
1.7 KiB
TypeScript
import { eq, type Db, conversations, messages } from '@mosaic/db';
|
|
|
|
export type Conversation = typeof conversations.$inferSelect;
|
|
export type NewConversation = typeof conversations.$inferInsert;
|
|
export type Message = typeof messages.$inferSelect;
|
|
export type NewMessage = typeof messages.$inferInsert;
|
|
|
|
export function createConversationsRepo(db: Db) {
|
|
return {
|
|
async findAll(userId: string): Promise<Conversation[]> {
|
|
return db.select().from(conversations).where(eq(conversations.userId, userId));
|
|
},
|
|
|
|
async findById(id: string): Promise<Conversation | undefined> {
|
|
const rows = await db.select().from(conversations).where(eq(conversations.id, id));
|
|
return rows[0];
|
|
},
|
|
|
|
async create(data: NewConversation): Promise<Conversation> {
|
|
const rows = await db.insert(conversations).values(data).returning();
|
|
return rows[0]!;
|
|
},
|
|
|
|
async update(id: string, data: Partial<NewConversation>): Promise<Conversation | undefined> {
|
|
const rows = await db
|
|
.update(conversations)
|
|
.set({ ...data, updatedAt: new Date() })
|
|
.where(eq(conversations.id, id))
|
|
.returning();
|
|
return rows[0];
|
|
},
|
|
|
|
async remove(id: string): Promise<boolean> {
|
|
const rows = await db.delete(conversations).where(eq(conversations.id, id)).returning();
|
|
return rows.length > 0;
|
|
},
|
|
|
|
async findMessages(conversationId: string): Promise<Message[]> {
|
|
return db.select().from(messages).where(eq(messages.conversationId, conversationId));
|
|
},
|
|
|
|
async addMessage(data: NewMessage): Promise<Message> {
|
|
const rows = await db.insert(messages).values(data).returning();
|
|
return rows[0]!;
|
|
},
|
|
};
|
|
}
|
|
|
|
export type ConversationsRepo = ReturnType<typeof createConversationsRepo>;
|