From 75c990adce146692afe0080e5801a4be9fcc2e3f Mon Sep 17 00:00:00 2001 From: chenos Date: Wed, 1 Jun 2022 21:37:48 +0800 Subject: [PATCH] fix: afterSync hook not triggered (#450) --- .../src/__tests__/sequelize-hooks.test.ts | 42 +++++++++++++++++++ packages/core/database/src/collection.ts | 2 +- packages/core/database/src/model-hook.ts | 12 +++--- 3 files changed, 50 insertions(+), 6 deletions(-) create mode 100644 packages/core/database/src/__tests__/sequelize-hooks.test.ts diff --git a/packages/core/database/src/__tests__/sequelize-hooks.test.ts b/packages/core/database/src/__tests__/sequelize-hooks.test.ts new file mode 100644 index 000000000..ca07f9d8a --- /dev/null +++ b/packages/core/database/src/__tests__/sequelize-hooks.test.ts @@ -0,0 +1,42 @@ +import { Database } from '../database'; +import { mockDatabase } from './index'; + +// TODO +describe('sequelize-hooks', () => { + let db: Database; + + beforeEach(async () => { + db = mockDatabase(); + await db.sync(); + }); + + afterEach(async () => { + await db.close(); + }); + + describe('afterSync', () => { + test('singular name', async () => { + const collection = db.collection({ + name: 't_test', + }); + const spy = jest.fn(); + db.on('t_test.afterSync', () => { + spy('afterSync'); + }); + await collection.sync(); + expect(spy).toHaveBeenCalledTimes(1); + }); + + test('plural name', async () => { + const collection = db.collection({ + name: 't_tests', + }); + const spy = jest.fn(); + db.on('t_tests.afterSync', () => { + spy('afterSync'); + }); + await collection.sync(); + expect(spy).toHaveBeenCalledTimes(1); + }); + }); +}); diff --git a/packages/core/database/src/collection.ts b/packages/core/database/src/collection.ts index 76f6b570e..922591d5b 100644 --- a/packages/core/database/src/collection.ts +++ b/packages/core/database/src/collection.ts @@ -1,7 +1,7 @@ import merge from 'deepmerge'; import { EventEmitter } from 'events'; import { default as lodash, default as _ } from 'lodash'; -import { col, ModelCtor, ModelOptions, SyncOptions } from 'sequelize'; +import { ModelCtor, ModelOptions, SyncOptions } from 'sequelize'; import { Database } from './database'; import { Field, FieldOptions } from './fields'; import { Model } from './model'; diff --git a/packages/core/database/src/model-hook.ts b/packages/core/database/src/model-hook.ts index c2b109dc6..d2f652941 100644 --- a/packages/core/database/src/model-hook.ts +++ b/packages/core/database/src/model-hook.ts @@ -30,18 +30,20 @@ export class ModelHook { if (arg?._previousDataValues) { return (arg).constructor.name; } - if (lodash.isPlainObject(arg)) { if (arg['model']) { return arg['model'].name; } - - if (lodash.get(arg, 'name.plural')) { - return lodash.get(arg, 'name.plural'); + const plural = arg?.name?.plural; + if (this.database.sequelize.isDefined(plural)) { + return plural; + } + const singular = arg?.name?.singular; + if (this.database.sequelize.isDefined(singular)) { + return singular; } } } - return null; }