From f20f6bf28c9172e1ff37137666e264dd5292f15c Mon Sep 17 00:00:00 2001 From: bigint <69431456+bigint@users.noreply.github.com> Date: Thu, 4 Jan 2024 13:11:22 +0530 Subject: [PATCH] feat: add db cleanup cron --- .github/workflows/cron-db-cleanup.yml | 21 +++++++++ apps/api/src/routes/internal/cleanup/db.ts | 55 ++++++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 .github/workflows/cron-db-cleanup.yml create mode 100644 apps/api/src/routes/internal/cleanup/db.ts diff --git a/.github/workflows/cron-db-cleanup.yml b/.github/workflows/cron-db-cleanup.yml new file mode 100644 index 000000000000..8121fa6757ec --- /dev/null +++ b/.github/workflows/cron-db-cleanup.yml @@ -0,0 +1,21 @@ +name: Cron - Cleanup DB + +on: + schedule: + - cron: '0 1 * * *' + workflow_dispatch: + +jobs: + cleanup: + name: Cleanup + runs-on: ubuntu-latest + steps: + - name: Cleanup DB + env: + SECRET: ${{ secrets.SECRET }} + run: | + curl -X POST \ + -H "Content-Type: application/json" \ + -H "Referer: https://hey.xyz" \ + -d '{"secret": "'"$SECRET"'"}' \ + https://api.hey.xyz/internal/cleanup/db diff --git a/apps/api/src/routes/internal/cleanup/db.ts b/apps/api/src/routes/internal/cleanup/db.ts new file mode 100644 index 000000000000..9514850fc7c4 --- /dev/null +++ b/apps/api/src/routes/internal/cleanup/db.ts @@ -0,0 +1,55 @@ +import type { Handler } from 'express'; + +import { Errors } from '@hey/data/errors'; +import logger from '@hey/lib/logger'; +import catchedError from '@utils/catchedError'; +import prisma from '@utils/prisma'; +import { invalidBody, noBody } from '@utils/responses'; +import { object, string } from 'zod'; + +type ExtensionRequest = { + secret: string; +}; + +const validationSchema = object({ + secret: string() +}); + +export const post: Handler = async (req, res) => { + const { body } = req; + + if (!body) { + return noBody(res); + } + + const validation = validationSchema.safeParse(body); + + if (!validation.success) { + return invalidBody(res); + } + + const { secret } = body as ExtensionRequest; + + if (secret !== process.env.SECRET) { + return res + .status(400) + .json({ error: Errors.InvalidSecret, success: false }); + } + + try { + // Cleanup ProfileRestriction + await prisma.profileRestriction.deleteMany({ + where: { isFlagged: false, isSuspended: false } + }); + + // Cleanup Preference + await prisma.preference.deleteMany({ + where: { highSignalNotificationFilter: false, isPride: false } + }); + logger.info('Cleaned up DB'); + + return res.status(200).json({ success: true }); + } catch (error) { + return catchedError(res, error); + } +};