const app = new (require('koa'))() const cors = require('@koa/cors') const koaBody = require('koa-body') const router = require('./routes') const timer = require('./timer') timer() app .use(async (ctx, next) => { try { await next() if (ctx.request.method === 'OPTIONS') { ctx.status = 204 } else if (!ctx.body && ctx.body !== false) { ctx.body = { code: -4, message: 'No Response Content' } } } catch (err) { const code = err.code const message = err.message if (code === -2) { ctx.body = { code, message: message || 'Invalid Argument' } } else if (code === -6) { ctx.body = { code, message: 'Method Not Allowed: ' + ctx.method } } else if (code === -7) { ctx.body = { code, message: 'No Permission' } } else if (code === -8) { ctx.body = { code, message: message || 'Request Third-party API Error' } } else if (code === -3 || code === -5 || code > 0) { ctx.body = { code, message: message || 'Unknown Error' } } else { console.log(err) ctx.body = { code: -1, message: 'Internal Server Error' } } } }) .on('error', (err, ctx) => ctx.body = { code: -1, message: 'Internal Server Error' }) .use(cors({ allowMethods: 'GET,POST,PUT,DELETE', maxAge: 600 })) .use(koaBody({ multipart: true, formLimit: '2mb', formidable: { keepExtensions: true, multiples: false } })) .use(router.routes()) .use(router.allowedMethods()) .listen(process.env.PORT || 81) .setTimeout(1000 * 60 * 5) /** * 全局返回错误码 * -1 未知错误(数据库错误) * -2 请求参数不符合接口要求 * -3 Token验证未通过 * -4 无返回内容 * -5 路由未找到 * -6 接口不支持该方法 * -7 操作权限不足 * -8 第三方接口调用出错 */