封装了很多东西:
const Koa = require('koa');
const config = require('./config');
const opn = require('opn');
const network = require('./libs/network');
const Router = require('koa-router');
const {post, upload} = require('./libs/body');
let server = new Koa();
(async ()=>{
server.context.db = await require('./libs/mysql')
server.context.redis = require('./libs/redis')
server.use(async (ctx, next)=>{
try{
await next();
}catch(e){
ctx.status = 500
ctx.body = 'internal server error'
}
})
let router = new Router()
// post + no upload
router.post('/api', post(), async ctx=>{
console.log(ctx.request.fields);
})
// post + upload
router.post(
'/upload',
...upload({
maxFileSize: 100 * 1024,
sizeExceed: async ctx=>{
ctx.body = 'aaa'
},
error: async ctx=>{
ctx.body = 'error'
}
}),
async ctx=>{
console.log(ctx.request.fields)
ctx.body = '上传成功'
}
)
server.use(router.routes())
// network
server.use(async ctx=>{
network.forEach(ip =>{
if(config.port == 80) {
console.log(`server running at ${ip}`);
}else{
console.log(`server running at ${ip}:${config.port}`);
}
})
})
server.listen(config.port)
// opn(`http://localhost:${config.port}`)
})();
body:
const body = require('koa-better-body');
const convert = require('koa-convert');
const config = require('../config');
module.exports={
post() {
return convert(body({
multipart: false,
buffer: false,
}));
},
upload(options) {
options = options || {};
options.uploadDir = options.uploadDir || config.upload_dir;
options.maxFileSize = options.maxFileSize || 20 * 1024 * 1024;
return [
async (ctx, next)=>{
try{
await next()
}catch(e){
console.log(e.message)
if(e.message.startsWith('maxFileSize exceeded')){
if(options.sizeExceed) {
await options.sizeExceed(ctx);
}else{
ctx.body = '文件过大'
}
}else{
if(options.error) {
await options.error(ctx, e)
}else{
throw e;
// ctx.body = '其他错误'
}
}
}
},
convert(body({
uploadDir: options.uploadDir,
maxFileSize: options.maxFileSize,
})),
];
}
}