Skip to content

Commit

Permalink
feat(repository): skip undefined property values for toJSON
Browse files Browse the repository at this point in the history
  • Loading branch information
raymondfeng committed Feb 27, 2020
1 parent 1e1a491 commit 8e049ec
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
6 changes: 6 additions & 0 deletions packages/repository/src/__tests__/unit/model/model.unit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,12 @@ describe('model', () => {
// notice that "extra" property was discarded from the output
});

it('skips properties with undefined values', () => {
const customer = createCustomer();
delete customer.email;
expect(customer.toJSON()).to.eql({id: '123'});
});

it('converts to json recursively', () => {
const customer = createCustomerWithContact();
expect(customer.toJSON()).to.eql({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,13 @@ describe('DefaultCrudRepository', () => {
expect(result?.toJSON()).to.eql(note.toJSON());
});

it('returns the correct instance with fields', async () => {
const repo = new DefaultCrudRepository(Note, ds);
const note = await repo.create({title: 'a-title', content: 'a-content'});
const result = await repo.findById(note.id, {fields: {title: true}});
expect(result?.toJSON()).to.eql({title: 'a-title'});
});

it('throws when the instance does not exist', async () => {
const repo = new DefaultCrudRepository(Note, ds);
await expect(repo.findById(999999)).to.be.rejectedWith({
Expand Down Expand Up @@ -656,7 +663,6 @@ describe('DefaultCrudRepository', () => {
expect(result.toJSON()).to.eql({
id: note.id,
title: 't4',
content: undefined,
});
});

Expand Down
5 changes: 4 additions & 1 deletion packages/repository/src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,10 @@ export abstract class Model {
}

const copyPropertyAsJson = (key: string) => {
json[key] = asJSON((this as AnyObject)[key]);
const val = asJSON((this as AnyObject)[key]);
if (val !== undefined) {
json[key] = val;
}
};

const json: AnyObject = {};
Expand Down

0 comments on commit 8e049ec

Please sign in to comment.