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

112 lines
2.7 KiB
TypeScript
Raw Normal View History

2022-07-28 18:56:02 +08:00
import compose from 'koa-compose';
import { requireModule } from '@nocobase/utils';
2020-10-24 15:34:43 +08:00
import { ActionName } from './action';
import { HandlerType } from './resourcer';
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;
private middlewares: HandlerType[] = [];
2020-10-24 15:34:43 +08:00
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 (ctx, next) => compose([handler, ...this.middlewares])(ctx, next);
}
use(middleware: HandlerType) {
this.middlewares.push(middleware);
}
disuse(middleware: HandlerType) {
this.middlewares.splice(this.middlewares.indexOf(middleware), 1);
2020-10-24 15:34:43 +08:00
}
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 function branch(
map: {
[key: string]: HandlerType;
} = {},
reducer: (ctx) => string,
options: {
keyNotFound?(ctx, next): void;
handlerNotSet?(ctx, next): void;
} = {},
): HandlerType {
return (ctx, next) => {
const key = reducer(ctx);
if (!key) {
return options.keyNotFound ? options.keyNotFound(ctx, next) : ctx.throw(404);
}
const handler = map[key];
if (!handler) {
return options.handlerNotSet ? options.handlerNotSet(ctx, next) : ctx.throw(404);
}
return handler(ctx, next);
};
}