next/server/api/story/[id]/set-viewed.ts
2024-01-04 20:49:51 -05:00

29 lines
760 B
TypeScript

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 {};
});