From 417fda7617de7ee0c65ef50e31f5672ee0caad65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=98=99=E2=97=A6=20The=20Tablet=20=E2=9D=80=20GamerGirla?= =?UTF-8?q?ndCo=20=E2=97=A6=E2=9D=A7?= Date: Thu, 4 Jan 2024 20:49:51 -0500 Subject: [PATCH] feat(api): add a route to update story views don't worry, there are duplicate/spam checks in place --- server/api/story/[id]/set-viewed.ts | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 server/api/story/[id]/set-viewed.ts diff --git a/server/api/story/[id]/set-viewed.ts b/server/api/story/[id]/set-viewed.ts new file mode 100644 index 0000000..609f825 --- /dev/null +++ b/server/api/story/[id]/set-viewed.ts @@ -0,0 +1,28 @@ +import { isIdNan } from "@server/middlewareButNotReally"; +import { Story } from "@models/stories"; + +export default eventHandler(async (ev) => { + const id = isIdNan(ev); + const ip = await getRequestIP(ev, { xForwardedFor: true }); + const storage = useStorage(`/story/${id}/viewMap`); + if (ev.context.currentUser) { + if (!(await storage.hasItem(`loggedIn/${ev.context.currentUser._id}`))) { + await Story.findByIdAndUpdate(id, { + $inc: { + views: 1, + }, + }); + } + await storage.setItem(`loggedIn/${ev.context.currentUser._id}`, Date.now()); + } else { + if (!(await storage.hasItem(`/loggedIn/${ip}`))) { + await Story.findByIdAndUpdate(id, { + $inc: { + views: 1, + }, + }); + } + await storage.setItem(ip, Date.now()); + } + return {}; +});