fix: toJSON with belongsTo Assoication (#287)
This commit is contained in:
parent
8b960c78d1
commit
d7856e76ab
60
packages/database/src/__tests__/model.test.ts
Normal file
60
packages/database/src/__tests__/model.test.ts
Normal 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();
|
||||
});
|
||||
});
|
||||
});
|
@ -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];
|
||||
|
Loading…
Reference in New Issue
Block a user