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);
}
}