feat: onAnyCollectionFieldDestroy

This commit is contained in:
Chareice 2022-02-09 20:30:00 +08:00 committed by chenos
parent 159775ff54
commit 61522a48fb
2 changed files with 69 additions and 0 deletions

View File

@ -166,6 +166,57 @@ describe('server hooks', () => {
expect(hookFn).toHaveBeenCalled(); expect(hookFn).toHaveBeenCalled();
}); });
it('should call server hooks onAnyCollectionFieldDestroy', async () => {
const menuSchema = {
'x-uid': 'menu',
'x-server-hooks': [
{
type: 'onAnyCollectionFieldDestroy',
collection: 'posts',
method: 'test1',
},
],
};
await uiSchemaRepository.create({
values: {
schema: menuSchema,
},
});
const PostModel = await db.getRepository('collections').create({
values: {
name: 'posts',
},
});
const fieldModel = await db.getRepository('fields').create({
values: {
name: 'title',
type: 'string',
collectionName: 'posts',
},
});
// @ts-ignore
await PostModel.migrate();
const serverHooks = uiSchemaPlugin.serverHooks;
const hookFn = jest.fn();
serverHooks.register('onAnyCollectionFieldDestroy', 'test1', hookFn);
// destroy a field
await db.getRepository('fields').destroy({
filter: {
name: 'title',
},
individualHooks: true,
});
expect(hookFn).toHaveBeenCalled();
});
it('should rollback after throw error', async () => { it('should rollback after throw error', async () => {
const testSchema = { const testSchema = {
'x-uid': 'test', 'x-uid': 'test',

View File

@ -18,6 +18,7 @@ export class ServerHooks {
listen() { listen() {
this.db.on('fields.afterDestroy', async (model, options) => { this.db.on('fields.afterDestroy', async (model, options) => {
await this.onCollectionFieldDestroy(model, options); await this.onCollectionFieldDestroy(model, options);
await this.onAnyCollectionFieldDestroy(model, options);
}); });
this.db.on('collections.afterDestroy', async (model, options) => { this.db.on('collections.afterDestroy', async (model, options) => {
@ -45,6 +46,23 @@ export class ServerHooks {
); );
} }
protected async onAnyCollectionFieldDestroy(fieldModel, options) {
const { transaction } = options;
const collectionName = fieldModel.get('collectionName');
await this.findHooksAndCall(
{
type: 'onAnyCollectionFieldDestroy',
collection: collectionName,
},
{
fieldInstance: fieldModel,
options,
},
transaction,
);
}
protected async onCollectionFieldDestroy(fieldModel, options) { protected async onCollectionFieldDestroy(fieldModel, options) {
const { transaction } = options; const { transaction } = options;
const collectionName = fieldModel.get('collectionName'); const collectionName = fieldModel.get('collectionName');