🐛 Delete polls in batches to avoid time out (#1627)

This commit is contained in:
Luke Vella 2025-03-10 11:10:36 +00:00 committed by GitHub
parent 8a192f74a1
commit 5d38be10e7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -3,6 +3,8 @@ import { NextResponse } from "next/server";
import { checkApiAuthorization } from "@/utils/api-auth";
const BATCH_SIZE = 100;
/**
* Remove polls and corresponding data that have been marked deleted for more than 7 days.
*/
@ -11,20 +13,42 @@ export async function POST() {
if (unauthorized) return unauthorized;
// First get the ids of all the polls that have been marked as deleted for at least 7 days
const deletedPolls = await prisma.poll.deleteMany({
where: {
deleted: true,
deletedAt: {
lt: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
let totalDeletedPolls = 0;
let hasMore = true;
const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
while (hasMore) {
const batch = await prisma.poll.findMany({
where: {
deleted: true,
deletedAt: {
lt: sevenDaysAgo,
},
},
},
});
select: { id: true },
take: BATCH_SIZE,
});
if (batch.length === 0) {
hasMore = false;
break;
}
const deleted = await prisma.poll.deleteMany({
where: {
id: { in: batch.map((poll) => poll.id) },
},
});
totalDeletedPolls += deleted.count;
}
return NextResponse.json({
success: true,
summary: {
deleted: {
polls: deletedPolls.count,
polls: totalDeletedPolls,
},
},
});