From 08c35a4646f1753e05b4fab1f06dcb96632a988e Mon Sep 17 00:00:00 2001 From: "tmayr@tmayr.com" Date: Mon, 23 Sep 2019 15:14:35 -0300 Subject: [PATCH] Added list support with prefix functionality --- lib/__tests__/kv.test.js | 47 ++++++++++++++++++++++++++++++++++++++++ lib/kv.js | 23 ++++++++++++++++++++ 2 files changed, 70 insertions(+) diff --git a/lib/__tests__/kv.test.js b/lib/__tests__/kv.test.js index 2547455..630ce7c 100644 --- a/lib/__tests__/kv.test.js +++ b/lib/__tests__/kv.test.js @@ -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() + }) }) diff --git a/lib/kv.js b/lib/kv.js index d81633a..c53624b 100644 --- a/lib/kv.js +++ b/lib/kv.js @@ -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 }