next/server/api/story/[id]/set-viewed.ts

29 lines
760 B
TypeScript
Raw Normal View History

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