feat: midway注解方式编写插件

This commit is contained in:
xiaojunnuo
2023-01-07 23:22:02 +08:00
parent e4ec4e1404
commit 52522f27e9
16 changed files with 156 additions and 238 deletions
+3
View File
@@ -13,3 +13,6 @@ export type AccessDefine = Registrable & {
export interface IAccessService {
getById(id: any): Promise<any>;
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface IAccess {}
+23 -55
View File
@@ -1,71 +1,39 @@
// src/decorator/memoryCache.decorator.ts
import {
attachClassMetadata,
attachPropertyDataToClass,
getClassMetadata,
listModule,
listPropertyDataFromClass,
saveClassMetadata,
saveModule,
} from "@midwayjs/decorator";
import { AccessDefine, AccessInputDefine } from "./api";
import { Decorator } from "../decorator";
import _ from "lodash";
import { accessRegistry } from "./registry";
// 提供一个唯一 key
export const ACCESS_CLASS_KEY = "decorator:access";
export const ACCESS_CLASS_KEY = "pipeline:access";
export const ACCESS_INPUT_KEY = "pipeline:access:input";
export function IsAccess(define: AccessDefine): ClassDecorator {
console.log("is access define:", define);
return (target: any) => {
console.log("is access load:", target);
// 将装饰的类,绑定到该装饰器,用于后续能获取到 class
saveModule(ACCESS_CLASS_KEY, target);
// 保存一些元数据信息,任意你希望存的东西
saveClassMetadata(
ACCESS_CLASS_KEY,
{
define,
},
target
);
target = Decorator.target(target);
const inputs: any = {};
const properties = Decorator.getClassProperties(target);
for (const property in properties) {
const input = Reflect.getMetadata(ACCESS_INPUT_KEY, target, property);
if (input) {
inputs[property] = input;
}
}
_.merge(define, { inputs });
Reflect.defineMetadata(ACCESS_CLASS_KEY, define, target);
target.define = define;
accessRegistry.register(define.name, {
define,
target,
});
};
}
export const ACCESS_INPUT_KEY = "decorator:access:input";
export function IsAccessInput(input?: AccessInputDefine): PropertyDecorator {
return (target, propertyKey) => {
attachPropertyDataToClass(ACCESS_INPUT_KEY, { input }, target, propertyKey, propertyKey as string);
attachClassMetadata(
ACCESS_CLASS_KEY,
{
inputs: {
[propertyKey]: input,
},
},
target
);
target = Decorator.target(target);
// const _type = Reflect.getMetadata("design:type", target, propertyKey);
Reflect.defineMetadata(ACCESS_INPUT_KEY, input, target, propertyKey);
};
}
export function registerAccess() {
const modules = listModule(ACCESS_CLASS_KEY);
for (const mod of modules) {
console.log("mod", mod);
const define = getClassMetadata(ACCESS_CLASS_KEY, mod);
console.log("define", define);
const inputs = listPropertyDataFromClass(ACCESS_INPUT_KEY, mod);
console.log("inputs", inputs);
for (const input of inputs) {
define.inputs = {};
_.merge(define.inputs, input.inputs);
}
accessRegistry.register(define.name, {
define,
target: mod,
});
}
}