From feea1bef48cf562eb7bd72df7d8842d67bcd02b3 Mon Sep 17 00:00:00 2001 From: Chareice Date: Tue, 7 Dec 2021 15:29:32 +0800 Subject: [PATCH] fix array field update --- .../__tests__/operator/array-operator.test.ts | 44 +++++++++++++++++++ packages/database/src/fields/array-field.ts | 10 ++--- 2 files changed, 48 insertions(+), 6 deletions(-) diff --git a/packages/database/src/__tests__/operator/array-operator.test.ts b/packages/database/src/__tests__/operator/array-operator.test.ts index 607202f22..3b247f442 100644 --- a/packages/database/src/__tests__/operator/array-operator.test.ts +++ b/packages/database/src/__tests__/operator/array-operator.test.ts @@ -40,6 +40,50 @@ describe('array field operator', function () { }); }); + test('array field update', async () => { + const Post = db.collection({ + name: 'posts', + fields: [ + { type: 'array', name: 'tags' }, + ], + }); + + + await db.sync({force: true}) + + await Post.repository.create({}) + const p1 = await Post.repository.create({ + values: { + tags: ['t1', 't2'] + } + }) + + + let result = await Post.repository.findOne({ + filter: { + 'tags.$match': ['t2', 't1'] + } + }) + + expect(result.get('id')).toEqual(p1.get('id')) + + await Post.repository.update({ + filterByPk: p1.get('id'), + values: { + tags: ['t3', 't2'] + } + }) + + result = await Post.repository.findOne({ + filter: { + 'tags.$match': ['t3', 't2'] + } + }) + + + expect(result.get('id')).toEqual(p1.get('id')) + }); + test('nested array field', async () => { const User = db.collection({ name: 'users', diff --git a/packages/database/src/fields/array-field.ts b/packages/database/src/fields/array-field.ts index a99a5a051..95f20c36d 100644 --- a/packages/database/src/fields/array-field.ts +++ b/packages/database/src/fields/array-field.ts @@ -12,6 +12,7 @@ export class ArrayField extends Field { sortValue(model) { const oldValue = model.get(this.options.name); + console.log({oldValue}) if (oldValue) { const newValue = oldValue.sort(); model.set(this.options.name, newValue); @@ -21,16 +22,13 @@ export class ArrayField extends Field { bind() { super.bind(); - if (this.isSqlite()) { - this.collection.model.addHook('beforeCreate', 'array-field-sort', this.sortValue.bind(this)); - } + this.on('beforeSave', this.sortValue.bind(this)); + } unbind() { super.unbind(); - if (this.isSqlite()) { - this.collection.model.removeHook('beforeCreate', 'array-field-sort'); - } + this.off('beforeSave', this.sortValue.bind(this)); } }