From b85e39b139089796d97be05ae1acfba1127caab5 Mon Sep 17 00:00:00 2001 From: Luke Edwards Date: Mon, 25 Apr 2022 10:59:14 -0700 Subject: [PATCH] chore(kv): extract `prefix?key` helper --- packages/worktop/src/cfw.kv.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/packages/worktop/src/cfw.kv.ts b/packages/worktop/src/cfw.kv.ts index f04d6b6..38d5d68 100644 --- a/packages/worktop/src/cfw.kv.ts +++ b/packages/worktop/src/cfw.kv.ts @@ -80,6 +80,10 @@ export async function until( } } +function keyname(prefix: string, key: string): string { + return !prefix || key.startsWith(prefix + '~') ? key : (prefix + '~' + key); +} + export class Entity implements E { readonly ns: KV.Namespace; readonly cache: Cache.Entity; @@ -101,7 +105,7 @@ export class Entity implements E { let { limit, prefix='' } = options; if (this.prefix) { - options.prefix = prefix.startsWith(this.prefix) ? prefix : (this.prefix + prefix); + options.prefix = keyname(this.prefix, prefix); } if (limit) { @@ -127,7 +131,7 @@ export class Entity implements E { } async get(key: string, format: Exclude = 'json'): Promise { - if (this.prefix) key = this.prefix + key; + key = keyname(this.prefix, key); let value: T|null; let res = this.ttl && await this.cache.get(key); @@ -148,7 +152,7 @@ export class Entity implements E { } async put(key: string, value: T|null): Promise { - if (this.prefix) key = this.prefix + key; + key = keyname(this.prefix, key); let input = Cache.normalize(value); let bool = await this.ns.put(key, input).then( @@ -170,7 +174,7 @@ export class Entity implements E { } async delete(key: string, format: Exclude = 'json'): Promise { - if (this.prefix) key = this.prefix + key; + key = keyname(this.prefix, key); let hasHook = typeof this.ondelete === 'function';