75 lines
1.7 KiB
JavaScript
Raw Normal View History

2020-03-15 18:32:04 +08:00
const Koa = require("koa");
const pinyin = require("pinyin");
2020-03-22 20:43:39 +08:00
const koaBody = require("koa-body");
2020-03-15 18:32:04 +08:00
const config = require("./config.js");
const app = new Koa();
console.log("配置为:" + JSON.stringify(config));
//错误处理,正常情况下200,未登录返回401其他返回500
app.use(async (ctx, next) => {
try {
await next();
ctx.res.statusCode = 200;
} catch (error) {
2020-03-22 20:43:39 +08:00
console.error(error);
2020-03-15 18:32:04 +08:00
if (error.message.startsWith("token")) {
2020-03-22 23:40:24 +08:00
ctx.status = 401;
2020-03-15 18:32:04 +08:00
} else {
2020-03-22 23:40:24 +08:00
ctx.status = 500;
2020-03-15 18:32:04 +08:00
}
2020-03-22 23:40:24 +08:00
ctx.body = error.message;
2020-03-15 18:32:04 +08:00
}
});
//检查token
app.use(async (ctx, next) => {
2020-03-22 23:40:24 +08:00
if (ctx.req.headers["token"] !== config.token) {
2020-03-15 18:32:04 +08:00
throw new Error("token校验失败");
}
2020-03-22 23:40:24 +08:00
if (ctx.req.url !== "/pinyinChange" || ctx.req.method !== "POST") {
throw new Error("路径或者方法错误");
2020-03-22 20:43:39 +08:00
}
2020-03-15 18:32:04 +08:00
await next();
});
2020-03-22 20:43:39 +08:00
app.use(koaBody());
2020-03-15 18:32:04 +08:00
//业务处理
app.use(async ctx => {
let body = ctx.request.body;
let style;
2020-03-22 20:43:39 +08:00
switch (body.config.style) {
2020-03-15 18:32:04 +08:00
case 1:
style = pinyin.STYLE_NORMAL;
break;
case 2:
style = pinyin.STYLE_TONE;
break;
case 3:
style = pinyin.STYLE_TONE2;
break;
case 4:
style = pinyin.STYLE_TO3NE;
break;
case 5:
style = pinyin.STYLE_INITIALS;
break;
case 5:
style = pinyin.STYLE_FIRST_LETTER;
break;
default:
style = pinyin.STYLE_NORMAL;
}
2020-03-22 20:43:39 +08:00
body.config.style = pinyin.STYLE_NORMAL;
2020-03-15 18:32:04 +08:00
let res = [];
2020-03-22 20:43:39 +08:00
body.strs.forEach(item => res.push(pinyin(item, body.config)));
2020-03-15 18:32:04 +08:00
ctx.body = res;
});
app.listen(config.port, () => {
console.log("app start at " + config.port);
});