tachybase_todo/packages/core/resourcer/src/middleware.ts

93 lines
2.2 KiB
TypeScript
Raw Normal View History

2020-10-24 15:34:43 +08:00
import { ActionName } from './action';
import { requireModule } from './utils';
import { HandlerType } from './resourcer';
import compose from 'koa-compose';
2020-10-24 15:34:43 +08:00
2021-12-06 21:23:34 +08:00
export type MiddlewareType = string | string[] | HandlerType | HandlerType[] | MiddlewareOptions | MiddlewareOptions[];
2020-10-24 15:34:43 +08:00
export interface MiddlewareOptions {
/**
* actions listgetcreateupdatedelete
*/
only?: Array<ActionName>;
/**
* actions listgetcreateupdatedelete
*/
except?: Array<ActionName>;
handler?: HandlerType | Function;
[key: string]: any;
}
export class Middleware {
protected options: MiddlewareOptions;
constructor(options: MiddlewareOptions | Function) {
options = requireModule(options);
if (typeof options === 'function') {
this.options = { handler: options };
} else {
this.options = options;
}
}
getHandler() {
const handler = requireModule(this.options.handler);
if (typeof handler !== 'function') {
throw new Error('Handler must be a function!');
}
return handler;
}
canAccess(name: ActionName) {
const { only = [], except = [] } = this.options;
if (only.length > 0) {
return only.includes(name);
}
if (except.length > 0) {
return !except.includes(name);
}
return true;
}
static toInstanceArray(middlewares: any): Middleware[] {
if (!middlewares) {
return [];
}
if (!Array.isArray(middlewares)) {
middlewares = [middlewares];
}
2021-12-06 21:23:34 +08:00
return middlewares.map((middleware) => {
2020-10-24 15:34:43 +08:00
if (middleware instanceof Middleware) {
return middleware;
}
if (typeof middleware === 'object') {
return new Middleware(middleware);
}
if (typeof middleware === 'function') {
2021-03-28 13:34:51 +08:00
return new Middleware({ handler: middleware });
2020-10-24 15:34:43 +08:00
}
});
}
}
2021-12-06 21:23:34 +08:00
export default Middleware;
export class MiddlewareManager {
protected middlewares: HandlerType[] = [];
compose() {
return (ctx, next) => compose(this.middlewares)(ctx, next);
}
use(middleware: HandlerType) {
this.middlewares.push(middleware);
}
unuse(middleware: HandlerType) {
this.middlewares.splice(this.middlewares.indexOf(middleware), 1);
}
}