tachybase_todo/packages/plugins/collection-manager/src/server.ts
ChengLei Shao e991b2965a
feat: collection inheritance (#1069)
* chore: test

* chore: inherited-collection class

* feat: collection inherit

* feat: collection inherit

* feat: inhertis sync runner

* test: get parents fields

* feat: collection inherit style promote

* feat: sync

* feat: sync alter table

* feat: pgOnly Test

* fix: child collection create api

* feat: replace parent field

* chore: reload parent fields

* test: reload collection test

* feat: details are displayed according to conditions

* fix: typo

* feat: inheritance map class

* chore: is parent node

* feat: display where child row created from

* fix: find with appends

* feat: add parent collection fields

* fix: create table

* feat: load fields for all children

* refactor: sync fields from parent

* test: has one field inhertis

* feat: replace child association target

* feat: should not replace child field when parent field update

* test: should update inherit field when parent field update

* feat: only the blocks directly inherited from the current data are displayed

* fix: inherit from multiple collections

* feat: only the blocks directly inherited from the current data are displayed

* fix: test

* feat: parent collection expend

* fix: test

* test: belongsToMany inherits

* test: belongsToMany inherits

* feat: block display

* feat: collection inherite

* feat: collection inherite

* feat: multiple inherits

* fix: sync runner

* feat: collection inherite

* feat: collecton inherits

* feat: cannot be modified after inheritance and saving

* feat: collection inherit for graph

* feat: collection inherits

* fix: drop inhertied field

* fix: should throw error when type conflit

* feat: output inherited fields

* feat: bulk update collection fields

* feat: collection fields

* feat: collection fields

* test: create relation with child table

* fix: test

* fix: test

* fix: test

* feat: style impove

* test: should not replace field with difference type

* feat: add text

* fix: throw error when replace field with difference type

* feat: overriding

* feat: kan bankanban group fields

* feat: calendar block fields

* feat: kan bankanban group fields

* fix: test

* feat: relationship fields

* feat: should delete child's field when parent field deleted

* feat: foreign key filter

* fix: build error & multiple inherit destory field

* fix: test

* chore: disable error

* feat: no recursive update associations (#1091)

* feat: update associations

* fix(collection-manager): should update uiSchema

* chore: flip if

* feat: mutile inherits

* feat: db dialect

* feat: inherits show by database

* chore: git hash into docker image

* fix: js gzip

* fix: dockerfile

* chore: error message

* feat: overriding

* feat: overriding

* feat: overriding

* feat: local

* feat: filter fields by interface

* fix: database logging env

* test: replace hasOne target

* feat: add view

* feat: local

* chore: enable error

* fix: update docs

Co-authored-by: katherinehhh <katherine_15995@163.com>
Co-authored-by: chenos <chenlinxh@gmail.com>
2022-11-16 12:53:58 +08:00

244 lines
7.4 KiB
TypeScript

import path from 'path';
import lodash from 'lodash';
import { UniqueConstraintError } from 'sequelize';
import PluginErrorHandler from '@nocobase/plugin-error-handler';
import { Plugin } from '@nocobase/server';
import { CollectionRepository } from '.';
import {
afterCreateForForeignKeyField,
afterCreateForReverseField,
beforeCreateForChildrenCollection,
beforeCreateForReverseField,
beforeDestroyForeignKey,
beforeInitOptions
} from './hooks';
import { CollectionModel, FieldModel } from './models';
import { InheritedCollection } from '@nocobase/database';
export class CollectionManagerPlugin extends Plugin {
async beforeLoad() {
this.app.db.registerModels({
CollectionModel,
FieldModel,
});
this.db.addMigrations({
namespace: 'collection-manager',
directory: path.resolve(__dirname, './migrations'),
context: {
plugin: this,
},
});
this.app.db.registerRepositories({
CollectionRepository,
});
this.app.db.on('fields.beforeUpdate', async (model, options) => {
const newValue = options.values;
if (
model.get('reverseKey') &&
lodash.get(newValue, 'reverseField') &&
!lodash.get(newValue, 'reverseField.key')
) {
const field = await this.app.db
.getModel('fields')
.findByPk(model.get('reverseKey'), { transaction: options.transaction });
if (field) {
throw new Error('cant update field without a reverseField key');
}
}
});
// 要在 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 collectionName = model.get('collectionName');
const collection = this.app.db.getCollection(collectionName);
if (!collection) {
return;
}
if (collection.isInherited() && (<InheritedCollection>collection).parentFields().has(model.get('name'))) {
model.set('overriding', true);
}
});
this.app.db.on('fields.beforeCreate', async (model, options) => {
const type = model.get('type');
const fn = beforeInitOptions[type];
if (fn) {
await fn(model, { database: this.app.db });
}
});
this.app.db.on('fields.afterCreate', afterCreateForReverseField(this.app.db));
this.app.db.on(
'collections.afterCreateWithAssociations',
async (model: CollectionModel, { context, transaction }) => {
if (context) {
await model.migrate({
transaction,
});
}
},
);
this.app.db.on('fields.afterCreate', async (model: FieldModel, { context, transaction }) => {
if (context) {
await model.migrate({
isNew: true,
transaction,
});
}
});
// after migrate
this.app.db.on('fields.afterCreate', afterCreateForForeignKeyField(this.app.db));
this.app.db.on('fields.afterUpdate', async (model: FieldModel, { context, transaction }) => {
const prevOptions = model.previous('options');
const currentOptions = model.get('options');
if (context) {
const prev = prevOptions['unique'];
const next = currentOptions['unique'];
if (Boolean(prev) !== Boolean(next)) {
await model.migrate({ transaction });
}
}
const prevDefaultValue = prevOptions['defaultValue'];
const currentDefaultValue = currentOptions['defaultValue'];
if (prevDefaultValue != currentDefaultValue) {
await model.syncDefaultValue({ transaction, defaultValue: currentDefaultValue });
}
const prevOnDelete = prevOptions['onDelete'];
const currentOnDelete = currentOptions['onDelete'];
if (prevOnDelete != currentOnDelete) {
await model.syncReferenceCheckOption({ transaction });
}
});
this.app.db.on('fields.afterSaveWithAssociations', async (model: FieldModel, { context, transaction }) => {
if (context) {
await model.load({ transaction });
}
});
// before field remove
this.app.db.on('fields.beforeDestroy', beforeDestroyForeignKey(this.app.db));
this.app.db.on('fields.beforeDestroy', async (model: FieldModel, options) => {
await model.remove(options);
});
this.app.db.on('collections.beforeDestroy', async (model: CollectionModel, options) => {
await model.remove(options);
});
this.app.db.on('fields.afterDestroy', async (model: FieldModel, options) => {
const { transaction } = options;
const collectionName = model.get('collectionName');
const childCollections = this.db.inheritanceMap.getChildren(collectionName);
const childShouldRemoveField = Array.from(childCollections).filter((item) => {
const parents = Array.from(this.db.inheritanceMap.getParents(item))
.map((parent) => {
const collection = this.db.getCollection(parent);
const field = collection.getField(model.get('name'));
return field;
})
.filter(Boolean);
return parents.length == 0;
});
await this.db.getCollection('fields').repository.destroy({
filter: {
name: model.get('name'),
collectionName: {
$in: childShouldRemoveField,
},
options: {
overriding: true,
},
},
transaction,
});
});
this.app.on('afterLoad', async (app, options) => {
if (options?.method === 'install') {
return;
}
const exists = await this.app.db.collectionExistsInDb('collections');
if (exists) {
try {
await this.app.db.getRepository<CollectionRepository>('collections').load();
} catch (error) {
await this.app.db.sync();
try {
await this.app.db.getRepository<CollectionRepository>('collections').load();
} catch (error) {
throw error;
}
}
}
});
this.app.resourcer.use(async (ctx, next) => {
const { resourceName, actionName } = ctx.action;
if (resourceName === 'collections.fields' && actionName === 'update') {
const { updateAssociationValues = [] } = ctx.action.params;
updateAssociationValues.push('uiSchema');
ctx.action.mergeParams({
updateAssociationValues,
});
}
await next();
});
this.app.acl.allow('collections', 'list', 'loggedIn');
this.app.acl.allow('collections', ['create', 'update', 'destroy'], 'allowConfigure');
}
async load() {
await this.app.db.import({
directory: path.resolve(__dirname, './collections'),
});
const errorHandlerPlugin = <PluginErrorHandler>this.app.getPlugin('error-handler');
errorHandlerPlugin.errorHandler.register(
(err) => {
return err instanceof UniqueConstraintError;
},
(err, ctx) => {
return ctx.throw(400, ctx.t(`The value of ${Object.keys(err.fields)} field duplicated`));
},
);
this.app.resourcer.use(async (ctx, next) => {
if (ctx.action.resourceName === 'collections.fields' && ['create', 'update'].includes(ctx.action.actionName)) {
ctx.action.mergeParams({
updateAssociationValues: ['uiSchema', 'reverseField'],
});
}
await next();
});
}
}
export default CollectionManagerPlugin;