nocobase/packages/resourcer/src/middleware.ts

78 lines
1.8 KiB
TypeScript
Raw Normal View History

2020-10-24 07:34:43 +00:00
import { ActionName } from './action';
import { requireModule } from './utils';
import { HandlerType } from './resourcer';
2021-03-28 05:34:51 +00:00
export type MiddlewareType = string | string[] | HandlerType | HandlerType[]
2020-10-24 07:34:43 +00:00
| MiddlewareOptions | MiddlewareOptions[];
export interface MiddlewareOptions {
2021-03-28 05:34:51 +00:00
2020-10-24 07:34:43 +00:00
/**
* 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];
}
return middlewares.map(middleware => {
if (middleware instanceof Middleware) {
return middleware;
}
if (typeof middleware === 'object') {
return new Middleware(middleware);
}
if (typeof middleware === 'function') {
2021-03-28 05:34:51 +00:00
return new Middleware({ handler: middleware });
2020-10-24 07:34:43 +00:00
}
});
}
}
export default Middleware;