Skip to content

Commit 7836d84

Browse files
committedMar 21, 2023
feat(flag): Find value from parameter with nested part into JSON content
This commit allows to find value directly in the JSON content of a flag. For example `flag(‘drive.office.enabled’)` will return true if we set `drive.office` with the JSON content `{enabled: true}`

File tree

2 files changed

+65
-4
lines changed

2 files changed

+65
-4
lines changed
 

‎packages/cozy-flags/src/store.js

+24-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import MicroEE from 'microee'
2+
23
import lsAdapter from './ls-adapter'
34

45
/**
@@ -34,10 +35,30 @@ class FlagStore {
3435

3536
get(name) {
3637
// eslint-disable-next-line no-prototype-builtins
37-
if (!this.store.hasOwnProperty(name)) {
38-
this.store[name] = null
38+
if (this.store.hasOwnProperty(name)) {
39+
return this.store[name]
40+
}
41+
42+
if (typeof name === 'string') {
43+
const nameElements = name.split('.')
44+
const size = nameElements.length
45+
for (let idx = size - 1; idx > 0; idx--) {
46+
const currentKey = nameElements.slice(0, idx).join('.')
47+
// eslint-disable-next-line no-prototype-builtins
48+
if (this.store.hasOwnProperty(currentKey)) {
49+
return nameElements
50+
.slice(idx, size)
51+
.reduce((previousValue, currentValue) => {
52+
// eslint-disable-next-line no-prototype-builtins
53+
return previousValue && previousValue.hasOwnProperty(currentValue)
54+
? previousValue[currentValue]
55+
: null
56+
}, this.store[currentKey])
57+
}
58+
}
3959
}
40-
return this.store[name]
60+
61+
return null
4162
}
4263

4364
set(name, value) {

‎packages/cozy-flags/src/tests.js

+41-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
import CozyClient from 'cozy-client'
21
import util from 'util'
32

3+
import CozyClient from 'cozy-client'
4+
45
export default function testFlagAPI(flag) {
56
afterEach(() => {
67
flag.reset()
@@ -30,6 +31,45 @@ export default function testFlagAPI(flag) {
3031
})
3132
})
3233
}
34+
35+
describe('part of the parameter is embedded in a json content', () => {
36+
beforeEach(() => {
37+
flag('test.obj1', {
38+
obj2: true,
39+
obj3: {
40+
obj4: {
41+
obj5: {
42+
obj6: {
43+
test: true
44+
},
45+
obj7: {
46+
test: null
47+
}
48+
}
49+
}
50+
}
51+
})
52+
})
53+
54+
it('should return the requested value when a part of the parameter is embedded', () => {
55+
expect(flag('test.obj1.obj2')).toBe(true)
56+
})
57+
58+
it('should return the requested value when multiple part of the parameter is embedded', () => {
59+
expect(flag('test.obj1.obj3.obj4.obj5')).toStrictEqual({
60+
obj6: {
61+
test: true
62+
},
63+
obj7: {
64+
test: null
65+
}
66+
})
67+
})
68+
69+
it('should return null when parameter not found', () => {
70+
expect(flag('test.obj2.obj3')).toBe(null)
71+
})
72+
})
3373
})
3474

3575
describe('listFlags', () => {

0 commit comments

Comments
 (0)
Please sign in to comment.