koa 中间件浅析

KOA

koa中间件调用

类似于redux中间价调用的洋葱模型,调用顺序和书写顺序一致,也可以看成是函数调用

const one = (ctx, next) => {
  console.log('>> one');
  next();
  console.log('<< one');
}

const two = (ctx, next) => {
  console.log('>> two');
  next();
  console.log('<< two');
}

const three = (ctx, next) => {
  console.log('>> three');
  next();
  console.log('<< three');
}

app.use(one);
app.use(two);
app.use(three);

输出:

>> one
>> two
>> three
<< three
<< two
<< one

中间件的编写原理

由于KOA中可以使用app.use来处理请求,而这个函数接受一个异步函数为参数

app.use(async (ctx, next) => {
	// do something
});

所以我们中间件的一般方法就是,一个函数,然后这个函数的返回值就是我们这个use所需要的同类型函数,例如我们自定义一个处理请求的函数,写法如下

export default function apiMiddleare(): Koa.Middleware<
  Koa.DefaultState,
  Koa.DefaultContext
> {
  // 这个函数就是use所需要的函数
  return (ctx: Context, next: Next): Promise<void> => {
    ctx.api = new Api(ctx);  // 我们在这个函数中对context重写并传入下一个中间件,所以接下来的中间件都可以调用ctx.api这个实例了
    return next();
  };
}


class Api {
  private ctx: Koa.Context;

  constructor(ctx: Koa.Context) {
    this.ctx = ctx;
  }

// 响应格式,重写context
  private res(code = 0, data: IAnyObject | null, msg = ''): void {
    this.ctx.status = 200;
    this.ctx.set('Content-Type', 'application/json');
    this.ctx.body = {
      code,
      msg,
      data,
    };
  }

  success(data: IAnyObject, msg = ''): void {
    return this.res(0, data, msg);
  }

  fail(code = -1, msg = ''): void {
    return this.res(code, null, msg);
  }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值