diff --git a/server/.env.test b/server/.env.test index 0c9bfd8..3c20cee 100644 --- a/server/.env.test +++ b/server/.env.test @@ -4,4 +4,7 @@ POST_LIMIT=50 POST_LIMIT_WINDOW_SECONDS=0.1 GET_LIMIT=20 GET_LIMIT_WINDOW_SECONDS=0.1 -LOG_LEVEL=warn \ No newline at end of file +LOG_LEVEL=warn + +# Make cleanup interval very long to avoid automatic cleanup during tests +CLEANUP_INTERVAL_SECONDS=99999 \ No newline at end of file diff --git a/server/src/app.integration.test.ts b/server/src/app.integration.test.ts index 8012ce7..85c4fe9 100644 --- a/server/src/app.integration.test.ts +++ b/server/src/app.integration.test.ts @@ -1,4 +1,4 @@ -import app from "./app"; +import app, { cleanExpiredNotes } from "./app"; import request from "supertest"; import { describe, it, expect } from "vitest"; import prisma from "./client"; @@ -136,3 +136,27 @@ describe("POST /api/note", () => { await new Promise((resolve) => setTimeout(resolve, 100)); }); }); + +describe("Clean expired notes", () => { + it("removes expired notes", async () => { + // insert a note with expiry date in the past using prisma + const { id } = await prisma.encryptedNote.create({ + data: { + ...testNote, + expire_time: new Date(0), + }, + }); + + // make request for note and check that response is 200 + let res = await request(app).get(`/api/note/${id}`); + expect(res.statusCode).toBe(200); + + // run cleanup + const nDeleted = await cleanExpiredNotes(); + expect(nDeleted).toBeGreaterThan(0); + + // make sure note is gone + res = await request(app).get(`/api/note/${id}`); + expect(res.statusCode).toBe(404); + }); +}); diff --git a/server/src/app.ts b/server/src/app.ts index a322e54..d127dbd 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -88,16 +88,8 @@ app.post("/api/note/", postLimiter, (req: Request, res: Response, next) => { .catch(next); }); -// For testing purposes -app.get("/api/test", (req, res, next) => { - res.status(200).send("Hello world!"); -}); - // Clean up expired notes periodically -const interval = - Math.max(parseInt(process.env.CLEANUP_INTERVAL_SECONDS) || 1, 1) * - 1000; -setInterval(async () => { +export async function cleanExpiredNotes(): Promise { try { logger.info("[Cleanup] Cleaning up expired notes..."); const deleted = await prisma.encryptedNote.deleteMany({ @@ -108,10 +100,16 @@ setInterval(async () => { }, }); logger.info(`[Cleanup] Deleted ${deleted.count} expired notes.`); + return deleted.count; } catch (err) { logger.error(`[Cleanup] Error cleaning expired notes:`); logger.error(err); } -}, interval); +} + +const interval = + Math.max(parseInt(process.env.CLEANUP_INTERVAL_SECONDS) || 1, 1) * + 1000; +setInterval(cleanExpiredNotes, interval); export default app;