fix: afterSync hook not triggered (#450)

This commit is contained in:
chenos 2022-06-01 21:37:48 +08:00 committed by GitHub
parent 838f4f18dc
commit 75c990adce
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 50 additions and 6 deletions

View File

@ -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);
});
});
});

View File

@ -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';

View File

@ -30,18 +30,20 @@ export class ModelHook {
if (arg?._previousDataValues) {
return (<Model>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;
}