From d7856e76ab612d5384b6cc59bccd4da3b991b484 Mon Sep 17 00:00:00 2001 From: ChengLei Shao Date: Tue, 12 Apr 2022 17:07:13 +0800 Subject: [PATCH] fix: toJSON with belongsTo Assoication (#287) --- packages/database/src/__tests__/model.test.ts | 60 +++++++++++++++++++ packages/database/src/model.ts | 2 +- 2 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 packages/database/src/__tests__/model.test.ts diff --git a/packages/database/src/__tests__/model.test.ts b/packages/database/src/__tests__/model.test.ts new file mode 100644 index 000000000..b6c9b9bf2 --- /dev/null +++ b/packages/database/src/__tests__/model.test.ts @@ -0,0 +1,60 @@ +import { Database, mockDatabase } from '@nocobase/database'; + +describe('model', () => { + let db: Database; + + beforeEach(async () => { + db = mockDatabase(); + }); + + afterEach(async () => { + await db.close(); + }); + + describe('toJSON', () => { + it('should return null when belongsTo association empty', async () => { + const user = db.collection({ + name: 'users', + fields: [ + { type: 'string', name: 'name' }, + { type: 'hasMany', name: 'posts' }, + ], + }); + + const posts = db.collection({ + name: 'posts', + fields: [ + { + type: 'string', + name: 'title', + }, + { + type: 'belongsTo', + name: 'user', + }, + ], + }); + + await db.sync(); + + const u1 = await db.getRepository('users').create({ + values: { + name: 'u1', + }, + }); + + await db.getRepository('posts').create({ + values: { + title: 'p1', + }, + }); + + const p1 = await db.getRepository('posts').findOne({ + appends: ['user'], + }); + + const p1JSON = p1.toJSON(); + expect(p1JSON['user']).toBeNull(); + }); + }); +}); diff --git a/packages/database/src/model.ts b/packages/database/src/model.ts index 0f31fa7e8..093737469 100644 --- a/packages/database/src/model.ts +++ b/packages/database/src/model.ts @@ -70,7 +70,7 @@ export class Model traverseJSON(item, opts)); } else { - result[key] = traverseJSON(data[key], opts); + result[key] = data[key] ? traverseJSON(data[key], opts) : null; } } else { result[key] = data[key];