加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
index.js 1.21 KB
一键复制 编辑 原始数据 按行查看 历史
yashujs 提交于 2024-03-16 01:40 . v12024-3-16-1_40_57
const Koa = require("koa");
const { bodyParser } = require("@koa/bodyparser");
const service = require("./service");
const loadConfig = require("./config/configLoader");
const config = loadConfig();
const app = new Koa();
app.use(async (ctx, next) => {
if (ctx.request.url !== "/translate") {
ctx.response.status = 404;
ctx.body = "error url, only /translate is provided";
return;
}
if (ctx.request.method !== "POST") {
ctx.status = 405;
ctx.body = "error method, only POST is provided";
return;
}
await next();
});
app.use(
bodyParser({
enableTypes: ["json"],
onError(err, ctx) {
ctx.throw(422, "error body type, should be json");
}
})
);
app.use(async (ctx, next) => {
const validationResult = await service.validateRequestBody(ctx);
if (validationResult.isValid) {
await next();
} else {
ctx.status = 400;
ctx.body = { message: validationResult.error };
}
});
app.use(async (ctx) => {
const result = await service.translate(ctx.request.body);
ctx.status = 200;
ctx.response.type = "application/json";
ctx.response.body = result;
});
const PORT = config.PORT;
app.listen(PORT, () => {
console.log("server is running at http://localhost:" + PORT);
});
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化