mirror of
https://github.com/lukevella/rallly.git
synced 2025-04-28 17:56:37 +02:00
🐛 Delete polls in batches to avoid time out (#1627)
This commit is contained in:
parent
8a192f74a1
commit
5d38be10e7
1 changed files with 32 additions and 8 deletions
|
@ -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,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
|
Loading…
Add table
Reference in a new issue