chatbot-template/lib/db/queries.ts

348 lines
7.7 KiB
TypeScript
Raw Normal View History

2024-11-27 15:11:20 +03:00
import 'server-only';
2024-10-11 18:00:22 +05:30
2024-11-05 17:15:51 +03:00
import { genSaltSync, hashSync } from 'bcrypt-ts';
2025-01-28 19:45:03 +05:30
import { and, asc, desc, eq, gt, gte, inArray } from 'drizzle-orm';
2024-11-05 17:15:51 +03:00
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
2024-10-11 18:00:22 +05:30
2024-11-05 17:15:51 +03:00
import {
user,
chat,
2024-11-15 12:18:17 -05:00
type User,
2024-11-05 17:15:51 +03:00
document,
2024-11-15 12:18:17 -05:00
type Suggestion,
suggestion,
2024-11-15 12:18:17 -05:00
type Message,
2024-11-05 17:15:51 +03:00
message,
vote,
} from './schema';
import { BlockKind } from '@/components/block';
2024-10-11 18:00:22 +05:30
// Optionally, if not using email/pass login, you can
// use the Drizzle adapter for Auth.js / NextAuth
// https://authjs.dev/reference/adapter/drizzle
2024-11-15 13:00:15 -05:00
// biome-ignore lint: Forbidden non-null assertion.
2024-11-20 21:22:42 +03:00
const client = postgres(process.env.POSTGRES_URL!);
2024-11-15 12:18:17 -05:00
const db = drizzle(client);
2024-10-11 18:00:22 +05:30
export async function getUser(email: string): Promise<Array<User>> {
try {
return await db.select().from(user).where(eq(user.email, email));
} catch (error) {
2024-11-05 17:15:51 +03:00
console.error('Failed to get user from database');
2024-10-11 18:00:22 +05:30
throw error;
}
}
export async function createUser(email: string, password: string) {
2024-11-15 12:18:17 -05:00
const salt = genSaltSync(10);
const hash = hashSync(password, salt);
2024-10-11 18:00:22 +05:30
try {
return await db.insert(user).values({ email, password: hash });
} catch (error) {
2024-11-05 17:15:51 +03:00
console.error('Failed to create user in database');
2024-10-11 18:00:22 +05:30
throw error;
}
}
export async function saveChat({
id,
userId,
2024-11-05 17:15:51 +03:00
title,
2024-10-11 18:00:22 +05:30
}: {
id: string;
userId: string;
2024-11-05 17:15:51 +03:00
title: string;
2024-10-11 18:00:22 +05:30
}) {
try {
return await db.insert(chat).values({
id,
createdAt: new Date(),
userId,
2024-11-05 17:15:51 +03:00
title,
2024-10-11 18:00:22 +05:30
});
} catch (error) {
2024-11-05 17:15:51 +03:00
console.error('Failed to save chat in database');
2024-10-11 18:00:22 +05:30
throw error;
}
}
export async function deleteChatById({ id }: { id: string }) {
try {
await db.delete(vote).where(eq(vote.chatId, id));
await db.delete(message).where(eq(message.chatId, id));
2024-10-11 18:00:22 +05:30
return await db.delete(chat).where(eq(chat.id, id));
} catch (error) {
2024-11-05 17:15:51 +03:00
console.error('Failed to delete chat by id from database');
2024-10-11 18:00:22 +05:30
throw error;
}
}
export async function getChatsByUserId({ id }: { id: string }) {
try {
return await db
.select()
.from(chat)
.where(eq(chat.userId, id))
.orderBy(desc(chat.createdAt));
} catch (error) {
2024-11-05 17:15:51 +03:00
console.error('Failed to get chats by user from database');
2024-10-11 18:00:22 +05:30
throw error;
}
}
export async function getChatById({ id }: { id: string }) {
try {
const [selectedChat] = await db.select().from(chat).where(eq(chat.id, id));
return selectedChat;
} catch (error) {
2024-11-05 17:15:51 +03:00
console.error('Failed to get chat by id from database');
throw error;
}
}
export async function saveMessages({ messages }: { messages: Array<Message> }) {
try {
return await db.insert(message).values(messages);
} catch (error) {
console.error('Failed to save messages in database', error);
throw error;
}
}
export async function getMessagesByChatId({ id }: { id: string }) {
try {
return await db
.select()
.from(message)
.where(eq(message.chatId, id))
.orderBy(asc(message.createdAt));
} catch (error) {
console.error('Failed to get messages by chat id from database', error);
throw error;
}
}
export async function voteMessage({
chatId,
messageId,
type,
}: {
chatId: string;
messageId: string;
type: 'up' | 'down';
}) {
try {
const [existingVote] = await db
.select()
.from(vote)
.where(and(eq(vote.messageId, messageId)));
if (existingVote) {
return await db
.update(vote)
2024-11-15 12:18:17 -05:00
.set({ isUpvoted: type === 'up' })
2024-11-05 17:15:51 +03:00
.where(and(eq(vote.messageId, messageId), eq(vote.chatId, chatId)));
}
2024-11-15 12:18:17 -05:00
return await db.insert(vote).values({
chatId,
messageId,
isUpvoted: type === 'up',
});
2024-11-05 17:15:51 +03:00
} catch (error) {
console.error('Failed to upvote message in database', error);
throw error;
}
}
export async function getVotesByChatId({ id }: { id: string }) {
try {
return await db.select().from(vote).where(eq(vote.chatId, id));
} catch (error) {
console.error('Failed to get votes by chat id from database', error);
2024-10-11 18:00:22 +05:30
throw error;
}
}
2024-10-30 16:01:24 +05:30
export async function saveDocument({
id,
title,
kind,
2024-10-30 16:01:24 +05:30
content,
userId,
}: {
id: string;
title: string;
kind: BlockKind;
2024-10-30 16:01:24 +05:30
content: string;
userId: string;
}) {
try {
return await db.insert(document).values({
id,
title,
kind,
2024-10-30 16:01:24 +05:30
content,
userId,
createdAt: new Date(),
});
} catch (error) {
2024-11-05 17:15:51 +03:00
console.error('Failed to save document in database');
2024-10-30 16:01:24 +05:30
throw error;
}
}
export async function getDocumentsById({ id }: { id: string }) {
try {
const documents = await db
.select()
.from(document)
.where(eq(document.id, id))
.orderBy(asc(document.createdAt));
return documents;
} catch (error) {
2024-11-05 17:15:51 +03:00
console.error('Failed to get document by id from database');
2024-10-30 16:01:24 +05:30
throw error;
}
}
export async function getDocumentById({ id }: { id: string }) {
try {
const [selectedDocument] = await db
.select()
.from(document)
.where(eq(document.id, id))
.orderBy(desc(document.createdAt));
return selectedDocument;
} catch (error) {
2024-11-05 17:15:51 +03:00
console.error('Failed to get document by id from database');
2024-10-30 16:01:24 +05:30
throw error;
}
}
export async function deleteDocumentsByIdAfterTimestamp({
id,
timestamp,
}: {
id: string;
timestamp: Date;
}) {
try {
await db
.delete(suggestion)
.where(
and(
eq(suggestion.documentId, id),
2024-11-15 13:00:15 -05:00
gt(suggestion.documentCreatedAt, timestamp),
),
);
2024-10-30 16:01:24 +05:30
return await db
.delete(document)
.where(and(eq(document.id, id), gt(document.createdAt, timestamp)));
} catch (error) {
console.error(
2024-11-15 13:00:15 -05:00
'Failed to delete documents by id after timestamp from database',
2024-10-30 16:01:24 +05:30
);
throw error;
}
}
export async function saveSuggestions({
suggestions,
}: {
suggestions: Array<Suggestion>;
}) {
try {
return await db.insert(suggestion).values(suggestions);
2024-10-30 16:01:24 +05:30
} catch (error) {
2024-11-05 17:15:51 +03:00
console.error('Failed to save suggestions in database');
2024-10-30 16:01:24 +05:30
throw error;
}
}
export async function getSuggestionsByDocumentId({
documentId,
}: {
documentId: string;
}) {
try {
return await db
.select()
.from(suggestion)
.where(and(eq(suggestion.documentId, documentId)));
2024-10-30 16:01:24 +05:30
} catch (error) {
console.error(
2024-11-15 13:00:15 -05:00
'Failed to get suggestions by document version from database',
2024-10-30 16:01:24 +05:30
);
throw error;
}
}
export async function getMessageById({ id }: { id: string }) {
try {
return await db.select().from(message).where(eq(message.id, id));
} catch (error) {
console.error('Failed to get message by id from database');
throw error;
}
}
export async function deleteMessagesByChatIdAfterTimestamp({
chatId,
timestamp,
}: {
chatId: string;
timestamp: Date;
}) {
try {
2025-01-28 19:45:03 +05:30
const messagesToDelete = await db
.select({ id: message.id })
.from(message)
.where(
and(eq(message.chatId, chatId), gte(message.createdAt, timestamp)),
);
2025-01-28 19:45:03 +05:30
const messageIds = messagesToDelete.map((message) => message.id);
if (messageIds.length > 0) {
await db
.delete(vote)
.where(
and(eq(vote.chatId, chatId), inArray(vote.messageId, messageIds)),
);
return await db
.delete(message)
.where(
and(eq(message.chatId, chatId), inArray(message.id, messageIds)),
);
}
} catch (error) {
console.error(
'Failed to delete messages by id after timestamp from database',
);
throw error;
}
}
export async function updateChatVisiblityById({
chatId,
visibility,
}: {
chatId: string;
visibility: 'private' | 'public';
}) {
try {
return await db.update(chat).set({ visibility }).where(eq(chat.id, chatId));
} catch (error) {
console.error('Failed to update chat visibility in database');
throw error;
}
}