|
| 1 | +import { qs } from '@root/utilities/qs' |
| 2 | +import { cookies } from 'next/headers' |
| 3 | + |
| 4 | +const { NEXT_PUBLIC_CMS_URL } = process.env |
| 5 | + |
| 6 | +async function clearDuplicateThreads() { |
| 7 | + const existingThreads = await fetch(`${NEXT_PUBLIC_CMS_URL}/api/community-help?depth=0&limit=0`) |
| 8 | + .then((res) => res.json()) |
| 9 | + .then((data) => |
| 10 | + data.docs.map((thread) => ({ |
| 11 | + id: thread.communityHelpType === 'discord' ? thread.discordID : thread.githubID, // Use respective IDs |
| 12 | + communityHelpType: thread.communityHelpType, |
| 13 | + uniqueID: thread.id, |
| 14 | + })), |
| 15 | + ) |
| 16 | + |
| 17 | + const threadGroups = existingThreads.reduce((acc, thread) => { |
| 18 | + const groupId = thread.id |
| 19 | + acc[groupId] = acc[groupId] || [] |
| 20 | + acc[groupId].push(thread) |
| 21 | + return acc |
| 22 | + }, {}) |
| 23 | + |
| 24 | + const threadsToDelete: string[] = [] |
| 25 | + const cleanedThreads = Object.values(threadGroups).map((group: any[]) => { |
| 26 | + if (group.length > 1) { |
| 27 | + threadsToDelete.push(...group.slice(1).map((thread) => thread.uniqueID)) // Flatten by spreading |
| 28 | + } |
| 29 | + return group[0] |
| 30 | + }) |
| 31 | + |
| 32 | + const cookieStore = await cookies() |
| 33 | + const token = cookieStore.get('payload-token') |
| 34 | + |
| 35 | + if (!token) { |
| 36 | + throw new Error('You are unauthorized, please log in.') |
| 37 | + } |
| 38 | + |
| 39 | + const batchNumber = 10 |
| 40 | + for (let i = 0; i < threadsToDelete.length; i += batchNumber) { |
| 41 | + const batch = threadsToDelete.slice(i, i + batchNumber) |
| 42 | + await Promise.all( |
| 43 | + batch.map(async (id) => { |
| 44 | + try { |
| 45 | + const res = await fetch( |
| 46 | + `${NEXT_PUBLIC_CMS_URL}/api/community-help?${qs.stringify({ |
| 47 | + depth: 0, |
| 48 | + where: { id: { equals: id } }, |
| 49 | + })}`, |
| 50 | + { |
| 51 | + credentials: 'include', |
| 52 | + headers: { |
| 53 | + Authorization: `JWT ${token.value}`, |
| 54 | + 'Content-Type': 'application/json', |
| 55 | + }, |
| 56 | + method: 'DELETE', |
| 57 | + }, |
| 58 | + ) |
| 59 | + if (!res.ok) { |
| 60 | + throw new Error(`Failed to delete thread with ID: ${id}`) |
| 61 | + } |
| 62 | + } catch (error) { |
| 63 | + console.error('Error deleting thread:', error) |
| 64 | + } |
| 65 | + }), |
| 66 | + ) |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +export default clearDuplicateThreads |
0 commit comments