feat: changed with associations (#943)

* feat: changed with associations

* fix: test error

* fix: test error

* fix: test
# Conflicts:
#	packages/core/database/src/model.ts
This commit is contained in:
chenos 2022-10-21 11:53:43 +08:00
parent 9c8922a26d
commit 1bdc29b706
3 changed files with 57 additions and 1 deletions

View File

@ -0,0 +1,46 @@
import Database from '../database';
import { mockDatabase } from '../mock-database';
describe('changedWithAssociations', () => {
let db: Database;
beforeEach(async () => {
db = mockDatabase();
await db.clean({ drop: true });
});
afterEach(async () => {
await db.close();
});
test('changedWithAssociations', async () => {
db.collection({
name: 'test',
fields: [
{
type: 'string',
name: 'n1',
},
{
type: 'string',
name: 'n2',
},
],
});
let changed = [];
db.on('test.afterCreateWithAssociations', (model, options) => {
changed = model.changedWithAssociations();
});
db.on('test.afterUpdateWithAssociations', (model, options) => {
changed = model.changedWithAssociations();
});
await db.sync();
const r = db.getRepository('test');
const m = await r.create({ values: { n1: 'a' } });
expect(changed.includes('n1')).toBeTruthy();
expect(m.changedWithAssociations()).toBeFalsy();
await r.update({ filterByTk: m.id, values: { n1: 'b', n2: 'c' } });
expect(changed).toEqual(['n1', 'n2']);
expect(m.changedWithAssociations()).toBeFalsy();
});
});

View File

@ -14,7 +14,7 @@ import {
Sequelize, Sequelize,
SyncOptions, SyncOptions,
Transactionable, Transactionable,
Utils, Utils
} from 'sequelize'; } from 'sequelize';
import { SequelizeStorage, Umzug } from 'umzug'; import { SequelizeStorage, Umzug } from 'umzug';
import { Collection, CollectionOptions, RepositoryType } from './collection'; import { Collection, CollectionOptions, RepositoryType } from './collection';
@ -232,6 +232,14 @@ export class Database extends EventEmitter implements AsyncEmitter {
opts.tableName = `${this.options.tablePrefix}${opts.tableName || opts.modelName || opts.name.plural}`; opts.tableName = `${this.options.tablePrefix}${opts.tableName || opts.modelName || opts.name.plural}`;
} }
}); });
this.on('afterCreate', async (instance) => {
instance?.toChangedWithAssociations?.();
});
this.on('afterUpdate', async (instance) => {
instance?.toChangedWithAssociations?.();
});
} }
addMigration(item: MigrationItem) { addMigration(item: MigrationItem) {

View File

@ -361,6 +361,7 @@ export class Repository<TModelAttributes extends {} = any, TCreationAttributes e
...options, ...options,
transaction, transaction,
}); });
instance.clearChangedWithAssociations();
} }
return instance; return instance;
@ -425,6 +426,7 @@ export class Repository<TModelAttributes extends {} = any, TCreationAttributes e
...options, ...options,
transaction, transaction,
}); });
instance.clearChangedWithAssociations();
} }
} }