Koa

文章目录
  1. 1. 常用库
  2. 2. 中间件&插件
    1. 2.1. 洋葱模型
    2. 2.2. 原理
  3. 3. 其他

常用框架有

  • express, koa
  • nestjs: 偏java的spring框架,依赖注入、官方集成了gql,微服务等功能(midway类似)
  • next.js / nuxt.js: SSR

常用库

  • koa-router
  • koa-static
  • koa-body
  • koa-session
  • koa-cors
  • koa-logger
  • koa-compress: 开启gzip
  • koa-jwt: jsonWebToken
  • koa-helmet: httpHeader安全相关(最好做在nginx层)
  • koa-convert: 将koa1和koa2插件互转
  • eggjs:基于koa,但是内置了很多适用于企业建站的插件;比如log和jwt

中间件&插件

app.use(logFn())

module.exports = function logFn (options) {
return function (ctx, next) {
// 如果是插件只执行一次
if (ctx.logFn) return next();
ctx.logFn = xxx
}
}

洋葱模型

function someMiddleware(ctx, next) {
// before code: 比如到达接口之前提前序列化一下ctx.body
next(); // 先去执行下一个中间件
// after code: 比如给response的值处理一下
}

原理

参考资料

let app = {
middlewares:[];//缓存队列
use(fn){//注册中间件
this.middlewares.push(fn);
}
}
app.use(koaStatic())
app.use(koaRouter())

// next就是middlewares里面的一个middlewareFn,这样子配合起来就可以构成洋葱模型

// 合并成一个连续执行函数
function compose (ms) {
return ms.reduce((a,b)=>{
return (arg)=>{
a(()=>{b(arg)})
}
});
}

compose(app.middlewares)()

其他

  • pm2部署代码
  • 错误监听:app.on(‘error’, (err, ctx) => {})
  • 最外层中间件处理所有中间件错误(洋葱模型最佳运用?)
const handler = async (ctx, next) => {
try {
await next();
} catch (err) {
ctx.response.status = err.statusCode;
ctx.response.body = {
message: err.message
}
}
}

const main = ctx => {
ctx.throw(500)
}

app.use(handler)
app.use(main)