Skip to content

Commit

Permalink
fix: SanData#get() return undefined when not found
Browse files Browse the repository at this point in the history
  • Loading branch information
harttle committed Mar 2, 2020
1 parent a44cc9f commit a54918f
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 13 deletions.
18 changes: 5 additions & 13 deletions src/models/san-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,11 @@ export class SanData {
}

get (path: string): any {
if (this.computed[path]) {
return this.computed[path].call({ data: this })
}
const seq = this.parseExpr(path)
let data = this.data
seq.forEach((name: string) => {
if (data[name] !== undefined && data[name] !== null) {
data = data[name]
} else {
return null
}
})
return data
if (this.computed[path]) return this.computed[path].call({ data: this })
return this.parseExpr(path).reduce(
(val: any, name: string) => val == null ? val : val[name],
this.data
)
}
set (path: string, value: string) {
const seq = this.parseExpr(path)
Expand Down
28 changes: 28 additions & 0 deletions test/unit/models/san-data.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { SanData } from '../../../src/models/san-data'

describe('models/SanData', () => {
it('should get directly defined data', () => {
const data = new SanData({ foo: 'FOO' }, {})
expect(data.get('foo')).toEqual('FOO')
})
it('should get nested data', () => {
const data = new SanData({ bar: { foo: 'FOO' } }, {})
expect(data.get('bar.foo')).toEqual('FOO')
})
it('should get computed data', () => {
const data = new SanData({}, { foo: () => 'FOO' })
expect(data.get('foo')).toEqual('FOO')
})
it('computed data should override defined data', () => {
const data = new SanData({ foo: 'FOO' }, { foo: () => 'Foo' })
expect(data.get('foo')).toEqual('Foo')
})
it('should return undefined if not found', () => {
const data = new SanData({ foo: 'FOO' }, {})
expect(data.get('bar')).toBeUndefined()
})
it('should return undefined if not found nested', () => {
const data = new SanData({ bar: { bar: 'FOO' } }, {})
expect(data.get('bar.foo')).toBeUndefined()
})
})

0 comments on commit a54918f

Please sign in to comment.