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