2022-01-19 02:02:52 +00:00
|
|
|
import path from 'path';
|
|
|
|
import { Plugin } from '@nocobase/server';
|
|
|
|
import { CollectionModel } from './models/collection';
|
|
|
|
import { FieldModel } from './models/field';
|
|
|
|
import beforeInitOptions from './hooks/beforeInitOptions';
|
|
|
|
import { beforeCreateForChildrenCollection } from './hooks/beforeCreateForChildrenCollection';
|
|
|
|
import { beforeCreateForReverseField } from './hooks/beforeCreateForReverseField';
|
|
|
|
import { afterCreateForReverseField } from './hooks/afterCreateForReverseField';
|
|
|
|
|
2022-01-24 06:10:35 +00:00
|
|
|
export * from './repositories/collection-repository';
|
|
|
|
|
2022-01-19 02:02:52 +00:00
|
|
|
export default class CollectionManagerPlugin extends Plugin {
|
|
|
|
async load() {
|
|
|
|
this.app.db.registerModels({
|
|
|
|
CollectionModel,
|
|
|
|
FieldModel,
|
|
|
|
});
|
2022-01-24 06:10:35 +00:00
|
|
|
|
2022-01-19 02:02:52 +00:00
|
|
|
await this.app.db.import({
|
|
|
|
directory: path.resolve(__dirname, './collections'),
|
|
|
|
});
|
2022-01-24 06:10:35 +00:00
|
|
|
|
2022-01-19 02:02:52 +00:00
|
|
|
// 要在 beforeInitOptions 之前处理
|
|
|
|
this.app.db.on('fields.beforeCreate', beforeCreateForReverseField(this.app.db));
|
|
|
|
this.app.db.on('fields.beforeCreate', beforeCreateForChildrenCollection(this.app.db));
|
|
|
|
this.app.db.on('fields.beforeCreate', async (model, options) => {
|
|
|
|
const type = model.get('type');
|
|
|
|
await this.app.db.emitAsync(`fields.${type}.beforeInitOptions`, model, options);
|
|
|
|
});
|
|
|
|
for (const key in beforeInitOptions) {
|
|
|
|
if (Object.prototype.hasOwnProperty.call(beforeInitOptions, key)) {
|
|
|
|
const fn = beforeInitOptions[key];
|
|
|
|
this.app.db.on(`fields.${key}.beforeInitOptions`, fn);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
this.app.db.on('fields.afterCreate', afterCreateForReverseField(this.app.db));
|
2022-01-24 06:10:35 +00:00
|
|
|
|
|
|
|
this.app.db.on('collections.afterCreateWithAssociations', async (model, options) => {
|
2022-01-19 02:02:52 +00:00
|
|
|
if (options.context) {
|
2022-01-22 13:15:23 +00:00
|
|
|
process.nextTick(async () => {
|
|
|
|
await model.migrate();
|
|
|
|
});
|
2022-01-19 02:02:52 +00:00
|
|
|
}
|
|
|
|
});
|
2022-01-24 06:10:35 +00:00
|
|
|
|
2022-01-19 02:02:52 +00:00
|
|
|
this.app.db.on('fields.afterCreate', async (model, options) => {
|
|
|
|
if (options.context) {
|
2022-01-22 13:15:23 +00:00
|
|
|
process.nextTick(async () => {
|
|
|
|
await model.migrate();
|
|
|
|
});
|
2022-01-19 02:02:52 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|