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

Commit

Permalink
Added browse support with prefix functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
tmayr committed Sep 23, 2019
1 parent 5993d55 commit 4acc5a9
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
47 changes: 47 additions & 0 deletions lib/__tests__/kv.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,4 +95,51 @@ describe('kv', () => {

cb()
})

test('KeyValueStore browse', async (cb) => {
const kv = new KeyValueStore()
kv.put('hello', 'world')
kv.put('foo', 'bar')

const value = await kv.browse()
expect(value).toEqual({
keys: [{ name: 'foo' }, { name: 'hello' }],
list_complete: true,
cursor: 'not-implemented',
})

cb()
})

test('KeyValueStore browse with prefix', async (cb) => {
const kv = new KeyValueStore()
kv.put('hello', 'world')
kv.put('foo', 'bar')
kv.put('foo:bar', 'foobard')

const value = await kv.browse({ prefix: 'foo' })
expect(value).toEqual({
keys: [{ name: 'foo' }, { name: 'foo:bar' }],
list_complete: true,
cursor: 'not-implemented',
})

cb()
})

test('KeyValueStore browse keys ordered lexicographically', async (cb) => {
const kv = new KeyValueStore()
kv.put('c', 'c')
kv.put('a', 'a')
kv.put('de', 'de')

const value = await kv.browse()
expect(value).toEqual({
keys: [{ name: 'a' }, { name: 'c' }, { name: 'de' }],
list_complete: true,
cursor: 'not-implemented',
})

cb()
})
})
23 changes: 23 additions & 0 deletions lib/kv.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,29 @@ class KeyValueStore {
fs.writeFileSync(this.path, JSON.stringify(data))
}
}

// Limit and Cursor are not implemented
browse (options = { prefix: null }) {
const keys = []

// Iterate over keys available
for (const key of this.store.keys()) {
// If options.prefix is set, skip any keys that don't match the prefix
if (options.prefix && key.indexOf(options.prefix) !== 0) continue

// Push the key if prefix matches or prefix is not set
keys.push(key)
}

// Order keys and format them as objects to match CF
const orderedKeys = keys.sort().map(key => ({ name: key }))

return Promise.resolve({
keys: orderedKeys,
cursor: 'not-implemented',
list_complete: true,
})
}
}

module.exports = { KeyValueStore }

0 comments on commit 4acc5a9

Please sign in to comment.