Skip to content

Instantly share code, notes, and snippets.

@mosch
Created April 3, 2022 08:35
Show Gist options
  • Save mosch/d8e26daf6060e225a28f96f2cd8b90f6 to your computer and use it in GitHub Desktop.
Save mosch/d8e26daf6060e225a28f96f2cd8b90f6 to your computer and use it in GitHub Desktop.
Cloudflare Typed Repository with Prefixa
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