2021-09-14 03:09:26 +00:00
|
|
|
import { uid } from '@nocobase/database';
|
|
|
|
import { Application } from './application';
|
2021-09-22 16:16:04 +00:00
|
|
|
import _ from 'lodash';
|
|
|
|
|
|
|
|
export interface IPlugin {
|
|
|
|
install?: (this: Plugin) => void;
|
|
|
|
load?: (this: Plugin) => void;
|
|
|
|
}
|
2021-09-14 03:09:26 +00:00
|
|
|
|
|
|
|
export interface PluginOptions {
|
|
|
|
name?: string;
|
|
|
|
activate?: boolean;
|
|
|
|
displayName?: string;
|
|
|
|
description?: string;
|
|
|
|
version?: string;
|
|
|
|
install?: (this: Plugin) => void;
|
|
|
|
load?: (this: Plugin) => void;
|
2021-09-22 16:16:04 +00:00
|
|
|
plugin?: typeof Plugin;
|
|
|
|
[key: string]: any;
|
2021-09-14 03:09:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export type PluginFn = (this: Plugin) => void;
|
|
|
|
|
2021-09-22 16:16:04 +00:00
|
|
|
export type PluginType = string | PluginFn | typeof Plugin;
|
2021-09-14 03:09:26 +00:00
|
|
|
|
|
|
|
export class Plugin implements IPlugin {
|
|
|
|
options: PluginOptions = {};
|
|
|
|
app: Application;
|
|
|
|
callbacks: IPlugin = {};
|
|
|
|
|
2021-09-22 16:16:04 +00:00
|
|
|
constructor(options?: PluginOptions & { app?: Application }) {
|
2021-09-14 03:09:26 +00:00
|
|
|
this.app = options?.app;
|
2021-09-22 16:16:04 +00:00
|
|
|
this.options = options;
|
|
|
|
this.callbacks = _.pick(options, ['load', 'activate']);
|
2021-09-14 03:09:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
getName() {
|
|
|
|
return this.options.name || uid();
|
|
|
|
}
|
|
|
|
|
|
|
|
async activate() {
|
|
|
|
this.options.activate = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
async install() {
|
|
|
|
await this.call('install');
|
|
|
|
}
|
|
|
|
|
|
|
|
async call(name: string) {
|
|
|
|
if (!this.callbacks[name]) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const callback = this.callbacks[name].bind(this);
|
|
|
|
await callback();
|
|
|
|
}
|
|
|
|
|
|
|
|
async load() {
|
|
|
|
await this.call('load');
|
|
|
|
}
|
|
|
|
}
|