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

Added list support with prefix functionality #122

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 list', async (cb) => {
const kv = new KeyValueStore()
kv.put('hello', 'world')
kv.put('foo', 'bar')

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

cb()
})

test('KeyValueStore list 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.list({ prefix: 'foo' })
expect(value).toEqual({
keys: [{ name: 'foo' }, { name: 'foo:bar' }],
list_complete: true,
cursor: 'not-implemented',
})

cb()
})

test('KeyValueStore list 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.list()
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
list (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 }