fix: toJSON with belongsTo Assoication (#287)

This commit is contained in:
ChengLei Shao 2022-04-12 17:07:13 +08:00 committed by GitHub
parent 8b960c78d1
commit d7856e76ab
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 61 additions and 1 deletions

View File

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

View File

@ -70,7 +70,7 @@ export class Model<TModelAttributes extends {} = any, TCreationAttributes extend
if (['HasMany', 'BelongsToMany'].includes(association.associationType)) {
result[key] = handleArray(data[key], opts).map((item) => traverseJSON(item, opts));
} else {
result[key] = traverseJSON(data[key], opts);
result[key] = data[key] ? traverseJSON(data[key], opts) : null;
}
} else {
result[key] = data[key];