Created
April 3, 2022 08:35
-
-
Save mosch/d8e26daf6060e225a28f96f2cd8b90f6 to your computer and use it in GitHub Desktop.
Cloudflare Typed Repository with Prefixa
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class RepositoryNamespace<Entity = string, Metadata = {}> { | |
private readonly ns: string | |
private readonly kv: KVNamespace | |
constructor(kv: KVNamespace, namespace: string) { | |
this.ns = namespace | |
this.kv = kv | |
} | |
put(key: string, entity: Entity) { | |
return this.kv.put(this.prefix(key), JSON.stringify(entity)) | |
} | |
get(key: string) { | |
return this.kv.get<Entity>(this.prefix(key), 'json') | |
} | |
getWithMetadata(key: string) { | |
return this.kv.getWithMetadata<Metadata>(this.prefix(key), 'json') | |
} | |
findFirst(key: string) { | |
return this.kv.list<Metadata>({ prefix: this.prefix(key), limit: 1 }) | |
} | |
list(prefix: string, options: Omit<KVNamespaceListOptions, 'prefix'>) { | |
return this.kv.list<Metadata>({ | |
...options, | |
prefix: this.prefix(prefix), | |
}) | |
} | |
private prefix = (key: string) => `${this.ns}/${key}` | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment