2020-11-11 18:16:18 +08:00
|
|
|
import Koa from 'koa';
|
2021-01-13 16:23:15 +08:00
|
|
|
import Database, { DatabaseOptions } from '@nocobase/database';
|
2020-11-12 11:48:27 +08:00
|
|
|
import Resourcer from '@nocobase/resourcer';
|
|
|
|
|
|
|
|
export interface ApplicationOptions {
|
2021-01-13 16:23:15 +08:00
|
|
|
database: DatabaseOptions;
|
|
|
|
resourcer?: any;
|
2020-11-12 11:48:27 +08:00
|
|
|
}
|
2020-11-11 18:16:18 +08:00
|
|
|
|
2021-01-13 16:23:15 +08:00
|
|
|
export class Application extends Koa {
|
2020-11-11 18:16:18 +08:00
|
|
|
|
2021-01-13 16:23:15 +08:00
|
|
|
public readonly database: Database;
|
|
|
|
|
|
|
|
public readonly resourcer: Resourcer;
|
2020-11-11 18:16:18 +08:00
|
|
|
|
2020-12-18 19:54:53 +08:00
|
|
|
protected plugins = new Map<string, any>();
|
2020-11-12 11:48:27 +08:00
|
|
|
|
2021-01-13 16:23:15 +08:00
|
|
|
constructor(options: ApplicationOptions) {
|
|
|
|
super();
|
|
|
|
this.database = new Database(options.database);
|
|
|
|
this.resourcer = new Resourcer();
|
|
|
|
// this.runHook('afterInit');
|
2020-12-18 19:54:53 +08:00
|
|
|
}
|
|
|
|
|
2021-01-13 16:23:15 +08:00
|
|
|
registerPlugin(key: string | object, plugin?: any) {
|
2020-12-18 19:54:53 +08:00
|
|
|
if (typeof key === 'object') {
|
|
|
|
Object.keys(key).forEach((k) => {
|
2021-01-13 16:23:15 +08:00
|
|
|
this.registerPlugin(k, key[k]);
|
2020-12-18 19:54:53 +08:00
|
|
|
});
|
|
|
|
} else {
|
2021-01-13 16:23:15 +08:00
|
|
|
const config = {};
|
|
|
|
if (Array.isArray(plugin)) {
|
|
|
|
const [entry, options = {}] = plugin;
|
|
|
|
Object.assign(config, { entry, options });
|
2020-12-18 09:04:40 +08:00
|
|
|
} else {
|
2021-01-13 16:23:15 +08:00
|
|
|
Object.assign(config, { entry: plugin, options: {} });
|
2020-11-11 18:16:18 +08:00
|
|
|
}
|
2021-01-13 16:23:15 +08:00
|
|
|
this.plugins.set(key, config);
|
2020-11-11 18:16:18 +08:00
|
|
|
}
|
|
|
|
}
|
2020-12-18 09:04:40 +08:00
|
|
|
|
2021-01-13 16:23:15 +08:00
|
|
|
getPluginInstance(key: string) {
|
|
|
|
const plugin = this.plugins.get(key);
|
|
|
|
return plugin && plugin.instance;
|
2020-12-18 19:54:53 +08:00
|
|
|
}
|
|
|
|
|
2021-01-13 16:23:15 +08:00
|
|
|
async loadPlugins() {
|
|
|
|
for (const plugin of this.plugins.values()) {
|
|
|
|
plugin.instance = await this.loadPlugin(plugin);
|
|
|
|
}
|
2020-12-18 19:54:53 +08:00
|
|
|
}
|
|
|
|
|
2021-01-13 16:23:15 +08:00
|
|
|
protected async loadPlugin({ entry, options = {} }: { entry: string | Function, options: any }) {
|
|
|
|
const main = typeof entry === 'function'
|
|
|
|
? entry
|
|
|
|
: require(`${entry}/${__filename.endsWith('.ts') ? 'src' : 'lib'}/server`).default;
|
2020-12-18 19:54:53 +08:00
|
|
|
|
2021-01-13 16:23:15 +08:00
|
|
|
return await main.call(this, options);
|
2020-12-18 09:04:40 +08:00
|
|
|
}
|
2020-11-11 18:16:18 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
export default Application;
|