Skip to content

Commit

Permalink
fix: edit messages with votes (vercel#737)
Browse files Browse the repository at this point in the history
  • Loading branch information
jeremyphilemon authored Jan 28, 2025
1 parent 2d47ffb commit 5bb62f1
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions lib/db/queries.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import 'server-only';

import { genSaltSync, hashSync } from 'bcrypt-ts';
import { and, asc, desc, eq, gt, gte } from 'drizzle-orm';
import { and, asc, desc, eq, gt, gte, inArray } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';

Expand Down Expand Up @@ -301,11 +301,28 @@ export async function deleteMessagesByChatIdAfterTimestamp({
timestamp: Date;
}) {
try {
return await db
.delete(message)
const messagesToDelete = await db
.select({ id: message.id })
.from(message)
.where(
and(eq(message.chatId, chatId), gte(message.createdAt, timestamp)),
);

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',
Expand Down

0 comments on commit 5bb62f1

Please sign in to comment.