Skip to content
This repository was archived by the owner on Jun 6, 2024. It is now read-only.

Commit 08c35a4

Browse files
committed
Added list support with prefix functionality
1 parent 5993d55 commit 08c35a4

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

lib/__tests__/kv.test.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,4 +95,51 @@ describe('kv', () => {
9595

9696
cb()
9797
})
98+
99+
test('KeyValueStore list', async (cb) => {
100+
const kv = new KeyValueStore()
101+
kv.put('hello', 'world')
102+
kv.put('foo', 'bar')
103+
104+
const value = await kv.list()
105+
expect(value).toEqual({
106+
keys: [{ name: 'foo' }, { name: 'hello' }],
107+
list_complete: true,
108+
cursor: 'not-implemented',
109+
})
110+
111+
cb()
112+
})
113+
114+
test('KeyValueStore list with prefix', async (cb) => {
115+
const kv = new KeyValueStore()
116+
kv.put('hello', 'world')
117+
kv.put('foo', 'bar')
118+
kv.put('foo:bar', 'foobard')
119+
120+
const value = await kv.list({ prefix: 'foo' })
121+
expect(value).toEqual({
122+
keys: [{ name: 'foo' }, { name: 'foo:bar' }],
123+
list_complete: true,
124+
cursor: 'not-implemented',
125+
})
126+
127+
cb()
128+
})
129+
130+
test('KeyValueStore list keys ordered lexicographically', async (cb) => {
131+
const kv = new KeyValueStore()
132+
kv.put('c', 'c')
133+
kv.put('a', 'a')
134+
kv.put('de', 'de')
135+
136+
const value = await kv.list()
137+
expect(value).toEqual({
138+
keys: [{ name: 'a' }, { name: 'c' }, { name: 'de' }],
139+
list_complete: true,
140+
cursor: 'not-implemented',
141+
})
142+
143+
cb()
144+
})
98145
})

lib/kv.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,29 @@ class KeyValueStore {
8282
fs.writeFileSync(this.path, JSON.stringify(data))
8383
}
8484
}
85+
86+
// Limit and Cursor are not implemented
87+
list (options = { prefix: null }) {
88+
const keys = []
89+
90+
// Iterate over keys available
91+
for (const key of this.store.keys()) {
92+
// If options.prefix is set, skip any keys that don't match the prefix
93+
if (options.prefix && key.indexOf(options.prefix) !== 0) continue
94+
95+
// Push the key if prefix matches or prefix is not set
96+
keys.push(key)
97+
}
98+
99+
// Order keys and format them as objects to match CF
100+
const orderedKeys = keys.sort().map(key => ({ name: key }))
101+
102+
return Promise.resolve({
103+
keys: orderedKeys,
104+
cursor: 'not-implemented',
105+
list_complete: true,
106+
})
107+
}
85108
}
86109

87110
module.exports = { KeyValueStore }

0 commit comments

Comments
 (0)