Files
itsc/pages/api/time/ranges/[id].js
2022-04-02 17:42:30 +08:00

79 lines
1.6 KiB
JavaScript

import {
deleteTimeRange,
getLimit,
authenticate,
update,
updateUsername,
updateUsernameWithLimit,
} from "../../../../libs/db";
import { addAPIQPS } from "../../../../libs/stats";
export default function handler(req, res) {
addAPIQPS();
// check if id is valid
const { id } = req.query;
if (id === undefined) {
res.status(400).json({
error: `缺少参数 id`,
});
return;
}
// delete method
if (req.method === "DELETE") {
// authenticate
const { token } = req.body;
if (!authenticate(token)) {
console.log("[DELETE] Authentication failed");
res.status(401).json({
error: `token ${token} 验证失败`,
});
return;
}
deleteTimeRange.run(id);
// update username
} else if (req.method === "PUT") {
const { username } = req.body;
// admin update username
const { token } = req.body;
if (authenticate(token)) {
const { name, username, id, range } = req.body;
const result = update.run(name, range, username, id);
res.status(200).json({
success: true,
});
return;
}
// check if id is valid
// check if username is valid
if (username === undefined) {
res.status(400).json({
error: `缺少参数 username`,
});
return;
}
try {
const limit = getLimit();
updateUsernameWithLimit(username, id, limit);
} catch (err) {
res.status(400).json({
error: err.message,
});
return;
}
// not allow
} else {
res.status(405).send({ error: "方法" + req.method + "不被允许" });
}
res.status(200).json({
success: true,
});
}