2020-11-11 15:23:39 +08:00
|
|
|
import path from 'path';
|
2020-12-01 20:11:39 +08:00
|
|
|
import { Application } from '@nocobase/server';
|
|
|
|
import hooks from './hooks';
|
|
|
|
import { registerModels } from '@nocobase/database';
|
|
|
|
import * as models from './models';
|
2020-11-11 15:23:39 +08:00
|
|
|
|
2020-12-01 20:11:39 +08:00
|
|
|
export default async function (this: Application, options = {}) {
|
|
|
|
const database = this.database;
|
|
|
|
const resourcer = this.resourcer;
|
|
|
|
// 提供全局的 models 注册机制
|
|
|
|
registerModels(models);
|
2020-11-11 15:23:39 +08:00
|
|
|
|
2020-11-11 20:57:18 +08:00
|
|
|
database.import({
|
2020-11-11 15:23:39 +08:00
|
|
|
directory: path.resolve(__dirname, 'collections'),
|
|
|
|
});
|
2020-12-01 20:11:39 +08:00
|
|
|
|
2020-12-21 14:15:58 +08:00
|
|
|
database.addHook('afterUpdateAssociations', async function(model, options) {
|
|
|
|
if (model instanceof models.FieldModel) {
|
|
|
|
if (model.get('interface') === 'subTable') {
|
|
|
|
const { migrate = true } = options;
|
|
|
|
const Collection = model.database.getModel('collections');
|
|
|
|
await Collection.load({...options, where: {name: model.get('collection_name')}});
|
|
|
|
migrate && await model.migrate(options);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2020-12-01 20:11:39 +08:00
|
|
|
Object.keys(hooks).forEach(modelName => {
|
|
|
|
const Model = database.getModel(modelName);
|
|
|
|
Object.keys(hooks[modelName]).forEach(hookKey => {
|
|
|
|
// TODO(types): 多层 map 映射类型定义较为复杂,暂时忽略
|
|
|
|
// @ts-ignore
|
|
|
|
Model.addHook(hookKey, hooks[modelName][hookKey]);
|
|
|
|
});
|
|
|
|
});
|
2020-12-23 20:29:11 +08:00
|
|
|
|
|
|
|
let initialized = false;
|
|
|
|
|
|
|
|
this.use(async (ctx, next) => {
|
|
|
|
if (!initialized) {
|
|
|
|
await database.getModel('collections').load({skipExisting: true});
|
|
|
|
initialized = true;
|
|
|
|
}
|
|
|
|
await next();
|
|
|
|
});
|
2020-11-11 15:23:39 +08:00
|
|
|
}
|