// Next.js API route support: https://nextjs.org/docs/api-routes/introduction import type { NextApiRequest, NextApiResponse } from "next"; import { store as storeProxy } from "@/store"; import config from "@/config"; export default function handler(req: NextApiRequest, res: NextApiResponse) { const store = storeProxy.get(); // console.log("api::store.null()", store); if (req.method === "POST") { if (!config.begin) { res.status(400).json({ error: "还没到开始时间哦", }); return; } const json = req.body; console.log("api::request: new request", json); if (json.checked) { let count = 0; for (const name in store) { if (store[name] == json.user) { count += 1; if (count >= config.limit) { res.status(403).json({ error: `超过选择数量限制,您至多选 ${config.limit} 个班次`, }); return; } } } // check whether the user repeatly select if (store[json.name] === json.user) { console.log("api::request: repeat select", json); res.status(403).json({ error: `您已经选择了这个班次,请勿重复选择`, }); return; } // check whether it is already occupied else if (store[json.name] !== undefined) { console.log("api::request: occupied", json); res.status(403).json({ error: `当前位置已被他人占用,请选择其他班次`, }); return; } store[json.name] = json.user; } else { // console.log(store, json); // check whether the request name match the taken name if (store[json.name] !== json.user) { res.status(403).json({ error: `您已经取消了这个班次,请勿重复点击复选框`, }) return; } delete store[json.name]; } } const resp: { occupied: string[], myselect: string[] } = { // try to fix occupied: [], myselect: [], }; for (const key in store) { if (store[key] !== req.query.name) { resp.occupied.push(key); } else { resp.myselect.push(key); } } res.status(200).json(resp); }