nocobase/packages/plugins/multi-app-manager/src/models/application.ts

77 lines
1.9 KiB
TypeScript
Raw Normal View History

import { Model, Transactionable } from '@nocobase/database';
import { Application } from '@nocobase/server';
import { AppDbCreator, AppOptionsFactory } from '../server';
export interface registerAppOptions extends Transactionable {
skipInstall?: boolean;
dbCreator: AppDbCreator;
appOptionsFactory: AppOptionsFactory;
}
export class ApplicationModel extends Model {
2023-02-16 01:46:23 +00:00
static async handleAppStart(mainApp: Application, app: Application, options: registerAppOptions) {
await mainApp.emit('beforeSubAppLoad', {
mainApp,
subApp: app,
});
await app.load();
if (!(await app.isInstalled())) {
await app.db.sync({
force: false,
alter: {
drop: false,
},
});
await app.install();
}
await app.start();
}
async registerToMainApp(mainApp: Application, options: registerAppOptions) {
const appName = this.get('name') as string;
const appOptions = (this.get('options') as any) || {};
2022-04-30 15:41:01 +00:00
const AppModel = this.constructor as typeof ApplicationModel;
const app = mainApp.appManager.createApplication(appName, {
...options.appOptionsFactory(appName, mainApp),
...appOptions,
2023-02-16 01:46:23 +00:00
name: appName,
});
const isInstalled = await (async () => {
try {
return await app.isInstalled();
} catch (e) {
if (e.message.includes('does not exist') || e.message.includes('Unknown database')) {
return false;
}
throw e;
}
})();
if (!isInstalled) {
await options.dbCreator(app);
}
2023-02-16 01:46:23 +00:00
await AppModel.handleAppStart(mainApp, app, options);
2022-04-30 15:41:01 +00:00
await AppModel.update(
{
status: 'running',
},
{
transaction: options.transaction,
where: {
[AppModel.primaryKeyAttribute]: this.get(AppModel.primaryKeyAttribute),
},
hooks: false,
},
);
}
}