Files
certd/packages/core/pipeline/src/registry/registry.ts
T

80 lines
1.5 KiB
TypeScript
Raw Normal View History

2022-10-26 09:02:47 +08:00
export type Registrable = {
name: string;
title: string;
desc?: string;
};
2022-10-26 23:29:10 +08:00
export abstract class AbstractRegistrable<T extends Registrable> {
// @ts-ignore
define: T;
getDefine(): T {
return this.define;
}
2022-10-26 09:02:47 +08:00
}
export class Registry<T extends typeof AbstractRegistrable> {
storage: {
[key: string]: T;
} = {};
2022-10-28 16:08:12 +08:00
install(pluginClass: T) {
if (pluginClass == null) {
2022-10-26 09:02:47 +08:00
return;
}
2022-10-26 23:29:10 +08:00
// @ts-ignore
2022-10-28 16:08:12 +08:00
const plugin = new pluginClass();
delete plugin.define;
const define = plugin.getDefine();
2022-10-26 23:29:10 +08:00
let defineName = define.name;
2022-10-26 09:02:47 +08:00
if (defineName == null) {
2022-10-28 16:08:12 +08:00
defineName = plugin.name;
2022-10-26 09:02:47 +08:00
}
2022-10-28 16:08:12 +08:00
this.register(defineName, pluginClass);
2022-10-26 09:02:47 +08:00
}
register(key: string, value: T) {
if (!key || value == null) {
return;
}
this.storage[key] = value;
}
get(name: string) {
if (!name) {
throw new Error("插件名称不能为空");
}
const plugin = this.storage[name];
if (!plugin) {
throw new Error(`插件${name}还未注册`);
}
return plugin;
}
getStorage() {
return this.storage;
}
2022-10-28 16:08:12 +08:00
getDefineList() {
const list = [];
for (const key in this.storage) {
2022-10-31 21:27:32 +08:00
const define = this.getDefine(key);
if (define) {
list.push({ ...define, key });
}
2022-10-28 16:08:12 +08:00
}
return list;
}
2022-10-31 21:27:32 +08:00
getDefine(key: string) {
const PluginClass = this.storage[key];
if (!PluginClass) {
return;
}
// @ts-ignore
const plugin = new PluginClass();
return plugin.define;
}
2022-10-26 09:02:47 +08:00
}