diff --git a/packages/plugin-ui-schema-storage/src/__tests__/server-hook.test.ts b/packages/plugin-ui-schema-storage/src/__tests__/server-hook.test.ts index fe5c34a3a..121e6c062 100644 --- a/packages/plugin-ui-schema-storage/src/__tests__/server-hook.test.ts +++ b/packages/plugin-ui-schema-storage/src/__tests__/server-hook.test.ts @@ -166,6 +166,57 @@ describe('server hooks', () => { 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 () => { const testSchema = { 'x-uid': 'test', diff --git a/packages/plugin-ui-schema-storage/src/server-hooks/index.ts b/packages/plugin-ui-schema-storage/src/server-hooks/index.ts index 5f46dc299..79eeda6ad 100644 --- a/packages/plugin-ui-schema-storage/src/server-hooks/index.ts +++ b/packages/plugin-ui-schema-storage/src/server-hooks/index.ts @@ -18,6 +18,7 @@ export class ServerHooks { listen() { this.db.on('fields.afterDestroy', async (model, options) => { await this.onCollectionFieldDestroy(model, options); + await this.onAnyCollectionFieldDestroy(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) { const { transaction } = options; const collectionName = fieldModel.get('collectionName');