nocobase/packages/core/resourcer/src/resource.ts

104 lines
2.3 KiB
TypeScript
Raw Normal View History

2020-10-24 07:34:43 +00:00
import _ from 'lodash';
import Resourcer from './resourcer';
import Middleware, { MiddlewareType } from './middleware';
import Action, { ActionName, ActionType } from './action';
export type ResourceType = 'single' | 'hasOne' | 'hasMany' | 'belongsTo' | 'belongsToMany';
export interface ResourceOptions {
/**
*
*/
name: string;
/**
* single
*/
type?: ResourceType;
/**
*
*/
actions?: {
[key: string]: ActionType;
2021-12-06 13:23:34 +00:00
};
2020-10-24 07:34:43 +00:00
/**
* actions listgetcreateupdatedelete
*/
only?: Array<ActionName>;
/**
* actions listgetcreateupdatedelete
*/
except?: Array<ActionName>;
/**
*
*/
middleware?: MiddlewareType;
/**
*
*/
middlewares?: MiddlewareType;
/**
*
*/
[key: string]: any;
}
export class Resource {
public readonly resourcer: Resourcer;
public readonly middlewares: Middleware[];
public readonly actions = new Map<ActionName, Action>();
public readonly options: ResourceOptions;
public readonly except: Array<ActionName>;
constructor(options: ResourceOptions, resourcer: Resourcer) {
const { middleware, middlewares, actions = {} } = options;
this.options = options;
this.resourcer = resourcer;
this.middlewares = Middleware.toInstanceArray(middleware || middlewares);
let excludes = [];
for (const [name, handler] of resourcer.getRegisteredHandlers()) {
if (!actions[name as string]) {
actions[name as string] = handler;
}
}
const { only = [], except = [] } = options;
if (except.length > 0) {
excludes = except;
} else if (only.length > 0) {
2021-12-06 13:23:34 +00:00
excludes = Object.keys(actions).filter((name) => !only.includes(name));
2020-10-24 07:34:43 +00:00
}
this.except = excludes;
this.actions = Action.toInstanceMap(_.omit(actions, excludes), this);
}
getName() {
return this.options.name;
}
getExcept() {
return this.except;
}
getAction(action: ActionName) {
if (this.except.includes(action)) {
throw new Error(`${action} action is not allowed`);
}
if (!this.actions.has(action)) {
throw new Error(`${action} action does not exist`);
}
return this.actions.get(action);
}
}
2021-12-06 13:23:34 +00:00
export default Resource;