Skip to content

Commit

Permalink
Improve toObject method
Browse files Browse the repository at this point in the history
When a property is either 'undefined' or 'null' it will return 'null' when using the toObject method.
Previously these values would throw an error
  • Loading branch information
bram-l committed Jan 18, 2018
1 parent 42c485b commit 3c05879
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/Model.js
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,11 @@ class Model
{
let value = this.get(key)

if (value.toObject)
if (typeof value === 'undefined')
{
value = null
}
else if (value && value.toObject)
{
value = value.toObject()
}
Expand Down
20 changes: 20 additions & 0 deletions test/model-to-object.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,26 @@ describe('Model toObject', () =>
expect(object).toEqual({ name: 'foo' })
})

it('returns an object with specified key when null', () =>
{
const instance = new Model({
name: null
})

const object = instance.toObject('name')

expect(object).toEqual({ name: null })
})

it('returns a null value for specified key when undefined', () =>
{
const instance = new Model()

const object = instance.toObject('name')

expect(object).toEqual({ name: null })
})

it('returns an object with specified keys', () =>
{
const instance = new Model({
Expand Down

0 comments on commit 3c05879

Please sign in to comment.