49a4ab4818
* refactor(plugin-users): improve extendibility of middlewares * fix(plugin-users): fix typo * fix: test error * fix: allowConfigure condition Co-authored-by: chenos <chenlinxh@gmail.com>
93 lines
2.2 KiB
TypeScript
93 lines
2.2 KiB
TypeScript
import { ActionName } from './action';
|
|
import { requireModule } from './utils';
|
|
import { HandlerType } from './resourcer';
|
|
import compose from 'koa-compose';
|
|
|
|
export type MiddlewareType = string | string[] | HandlerType | HandlerType[] | MiddlewareOptions | MiddlewareOptions[];
|
|
|
|
export interface MiddlewareOptions {
|
|
/**
|
|
* actions 白名单,默认有 list、get、create、update、delete
|
|
*/
|
|
only?: Array<ActionName>;
|
|
|
|
/**
|
|
* actions 黑名单,默认有 list、get、create、update、delete
|
|
*/
|
|
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') {
|
|
return new Middleware({ handler: middleware });
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|