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

358 lines
8.4 KiB
TypeScript
Raw Normal View History

import { requireModule, Toposort, ToposortOptions } from '@nocobase/utils';
2020-10-24 15:34:43 +08:00
import glob from 'glob';
import compose from 'koa-compose';
import _ from 'lodash';
import { pathToRegexp } from 'path-to-regexp';
2020-10-24 15:34:43 +08:00
import Action, { ActionName } from './action';
import Resource, { ResourceOptions } from './resource';
import { getNameByParams, ParsedParams, parseQuery, parseRequest } from './utils';
2020-10-24 15:34:43 +08:00
export interface ResourcerContext {
resourcer?: Resourcer;
action?: Action;
[key: string]: any;
}
export interface KoaMiddlewareOptions {
/**
*
*/
prefix?: string;
/**
* resource name
2021-12-06 21:23:34 +08:00
*
2020-10-24 15:34:43 +08:00
* relatedTable ? relatedTable.table : table
*/
nameRule?: (params: ParsedParams) => string;
2020-10-24 15:34:43 +08:00
/**
2021-09-09 12:48:01 +08:00
* action name
2021-12-06 21:23:34 +08:00
*
2021-09-09 12:48:01 +08:00
*
2021-12-06 21:23:34 +08:00
*
2021-09-09 12:48:01 +08:00
* - list
* - create
* - get
* - update
* - delete
2020-10-24 15:34:43 +08:00
*/
2021-09-09 12:48:01 +08:00
accessors?: {
/**
*
*/
list?: string;
/**
*
*/
create?: string;
/**
*
*/
get?: string;
/**
*
*/
update?: string;
/**
*
*/
delete?: string;
};
}
export interface ResourcerOptions {
/**
*
*/
prefix?: string;
2020-10-24 15:34:43 +08:00
/**
* action name
2021-12-06 21:23:34 +08:00
*
2020-10-24 15:34:43 +08:00
*
2021-12-06 21:23:34 +08:00
*
2020-10-24 15:34:43 +08:00
* - list
* - create
* - get
* - update
* - delete
*/
accessors?: {
/**
*
*/
list?: string;
/**
*
*/
create?: string;
/**
*
*/
get?: string;
/**
*
*/
update?: string;
/**
*
*/
delete?: string;
};
}
export interface ExecuteOptions {
/**
*
*/
resource: string;
/**
* action name
2021-12-06 21:23:34 +08:00
*
2020-10-24 15:34:43 +08:00
*
* - list
* - create
* - get
* - update
* - delete
*/
action: ActionName;
}
export type HandlerType = (ctx: ResourcerContext, next: () => Promise<any>) => any;
export interface Handlers {
[key: string]: HandlerType;
}
export interface ImportOptions {
/**
*
*/
directory: string;
/**
* ['js', 'ts', 'json']
*/
extensions?: string[];
}
export class Resourcer {
protected resources = new Map<string, Resource>();
/**
* action handlers
*/
protected handlers = new Map<ActionName, any>();
protected actionHandlers = new Map<ActionName, any>();
protected middlewareHandlers = new Map<string, any>();
protected middlewares: Toposort<any>;
2020-10-24 15:34:43 +08:00
2021-09-09 12:48:01 +08:00
public readonly options: ResourcerOptions;
constructor(options: ResourcerOptions = {}) {
this.options = options;
this.middlewares = new Toposort<any>();
2021-09-09 12:48:01 +08:00
}
2020-10-24 15:34:43 +08:00
/**
* resource
2021-12-06 21:23:34 +08:00
*
2020-10-24 15:34:43 +08:00
* TODO: 配置的文件驱动现在会全部初始化
2021-12-06 21:23:34 +08:00
*
2020-10-24 15:34:43 +08:00
* @param {object} [options]
* @param {string} [options.directory]
* @param {array} [options.extensions = ['js', 'ts', 'json']]
*/
public import(options: ImportOptions): Map<string, Resource> {
const { extensions = ['js', 'ts', 'json'], directory } = options;
const patten = `${directory}/*.{${extensions.join(',')}}`;
const files = glob.sync(patten, {
2021-12-06 21:23:34 +08:00
ignore: ['**/*.d.ts'],
});
2020-10-24 15:34:43 +08:00
const resources = new Map<string, Resource>();
files.forEach((file: string) => {
const options = requireModule(file);
const table = this.define(typeof options === 'function' ? options(this) : options);
resources.set(table.getName(), table);
});
return resources;
}
/**
* resource
2021-12-06 21:23:34 +08:00
*
* @param name
* @param options
2020-10-24 15:34:43 +08:00
*/
define(options: ResourceOptions) {
const { name } = options;
const resource = new Resource(options, this);
this.resources.set(name, resource);
return resource;
}
isDefined(name: string) {
return this.resources.has(name);
}
removeResource(name) {
return this.resources.delete(name);
}
2021-09-09 12:48:01 +08:00
registerAction(name: ActionName, handler: HandlerType) {
this.registerActionHandler(name, handler);
}
registerActions(handlers: Handlers) {
this.registerActionHandlers(handlers);
}
2020-10-24 15:34:43 +08:00
/**
* action handlers
2021-12-06 21:23:34 +08:00
*
* @param handlers
2020-10-24 15:34:43 +08:00
*/
registerActionHandlers(handlers: Handlers) {
for (const [name, handler] of Object.entries(handlers)) {
this.registerActionHandler(name, handler);
}
2020-10-24 15:34:43 +08:00
}
registerActionHandler(name: ActionName, handler: HandlerType) {
this.actionHandlers.set(name, handler);
}
2020-10-24 15:34:43 +08:00
getRegisteredHandler(name: ActionName) {
return this.actionHandlers.get(name);
2020-10-24 15:34:43 +08:00
}
getRegisteredHandlers() {
return this.actionHandlers;
2020-10-24 15:34:43 +08:00
}
getResource(name: string): Resource {
if (!this.resources.has(name)) {
throw new Error(`${name} resource does not exist`);
}
return this.resources.get(name);
}
getAction(name: string, action: ActionName): Action {
// 支持注册局部 action
if (this.actionHandlers.has(`${name}:${action}`)) {
return this.getResource(name).getAction(`${name}:${action}`);
}
2020-10-24 15:34:43 +08:00
return this.getResource(name).getAction(action);
}
getMiddlewares() {
return this.middlewares.nodes;
2020-10-24 15:34:43 +08:00
}
use(middlewares: HandlerType | HandlerType[], options: ToposortOptions = {}) {
this.middlewares.add(middlewares, options);
2020-10-24 15:34:43 +08:00
}
2021-09-09 12:48:01 +08:00
restApiMiddleware(options: KoaMiddlewareOptions = {}) {
const { prefix, accessors } = options;
const restApiMiddleware = async (ctx: ResourcerContext, next: () => Promise<any>) => {
2020-10-24 15:34:43 +08:00
ctx.resourcer = this;
2021-12-06 21:23:34 +08:00
let params = parseRequest(
{
path: ctx.request.path,
method: ctx.request.method,
},
{
prefix: this.options.prefix || prefix,
accessors: this.options.accessors || accessors,
},
);
2020-10-24 15:34:43 +08:00
if (!params) {
return next();
}
try {
2021-09-09 12:48:01 +08:00
const resource = this.getResource(getNameByParams(params));
2020-10-24 15:34:43 +08:00
// 为关系资源时,暂时需要再执行一遍 parseRequest
2021-09-09 12:48:01 +08:00
if (resource.options.type && resource.options.type !== 'single') {
2021-12-06 21:23:34 +08:00
params = parseRequest(
{
path: ctx.request.path,
method: ctx.request.method,
type: resource.options.type,
},
{
prefix: this.options.prefix || prefix,
accessors: this.options.accessors || accessors,
},
);
2020-10-24 15:34:43 +08:00
if (!params) {
return next();
}
}
// action 需要 clone 之后再赋给 ctx
2021-09-09 12:48:01 +08:00
ctx.action = this.getAction(getNameByParams(params), params.actionName).clone();
2020-10-24 15:34:43 +08:00
ctx.action.setContext(ctx);
ctx.action.actionName = params.actionName;
ctx.action.resourceOf = params.associatedIndex;
ctx.action.resourceName = params.associatedName
? `${params.associatedName}.${params.resourceName}`
: params.resourceName;
ctx.action.params.filterByTk = params.resourceIndex;
const query = parseQuery(ctx.request.querystring);
2020-10-24 15:34:43 +08:00
if (pathToRegexp('/resourcer/{:associatedName.}?:resourceName{\\::actionName}').test(ctx.request.path)) {
ctx.action.mergeParams({
2020-10-24 15:34:43 +08:00
...query,
...params,
...ctx.request.body,
});
} else {
ctx.action.mergeParams({
2020-10-24 15:34:43 +08:00
...query,
...params,
...(_.isEmpty(ctx.request.body) ? {} : { values: ctx.request.body }),
2020-10-24 15:34:43 +08:00
});
}
return compose(ctx.action.getHandlers())(ctx, next);
} catch (error) {
return next();
}
2021-09-09 12:48:01 +08:00
};
return restApiMiddleware;
}
middleware(options: KoaMiddlewareOptions = {}) {
return this.restApiMiddleware(options);
2020-10-24 15:34:43 +08:00
}
/**
* API
2021-12-06 21:23:34 +08:00
*
* @param options
* @param context
* @param next
2020-10-24 15:34:43 +08:00
*/
async execute(options: ExecuteOptions, context: ResourcerContext = {}, next?: any) {
const { resource, action } = options;
context.resourcer = this;
context.action = this.getAction(resource, action);
return await context.action.execute(context, next);
}
}
export default Resourcer;