From 74d1f222f5c5e6b5b8bd5c89c3892e5305f4accc Mon Sep 17 00:00:00 2001 From: Marcus Hanses Date: Wed, 12 Feb 2025 18:42:39 +0100 Subject: [PATCH] Optimize indexed kv. --- KeyValueStore/Indexed/index.ts | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/KeyValueStore/Indexed/index.ts b/KeyValueStore/Indexed/index.ts index c05efcb..ac1dcd7 100644 --- a/KeyValueStore/Indexed/index.ts +++ b/KeyValueStore/Indexed/index.ts @@ -12,14 +12,11 @@ export class Indexed implements KeyValueStore async set(key: string, value?: V, options?: { retention?: TimeSpan; meta?: M }): Promise { const old = (await this.data.get(key))?.value - if (old) { - await this.data.set(key) - await Promise.all((Object.values(this.indexes) as Index[]).map(index => index.set(old))) - } - if (value) { + if (value) await this.data.set(key, value, options) - await Promise.all((Object.values(this.indexes) as Index[]).map(index => index.set(value, key, options))) - } + else if (old) + await this.data.set(key) + await Promise.all(Object.values>(this.indexes).map(index => index.set(value, old, key, options))) } async get(key: string, index?: I): Promise<{ value: V; meta?: M | undefined } | undefined> { let result: { value: V; meta?: M | undefined } | undefined @@ -57,14 +54,18 @@ export class Indexed implements KeyValueStore { constructor(private index: (value: V) => string | undefined, private backend: KeyValueStore) {} - set(value: V): Promise - set(value: V, key: string, options?: { retention?: TimeSpan | undefined }): Promise - async set(value: V, key?: string, options?: { retention?: TimeSpan | undefined }): Promise { - const index = this.index(value) - if (key && index) + async set( + value: V | undefined, + oldValue: V | undefined, + key: string, + options?: { retention?: TimeSpan | undefined } + ): Promise { + const index = value && this.index(value) + const oldIndex = oldValue && this.index(oldValue) + if (oldIndex && (!index || index !== oldIndex)) + await this.backend.set(oldIndex) + if (index) await this.backend.set(index, key, options) - else if (index) - await this.backend.set(index) } async get(key: string): Promise { return (await this.backend.get(key))?.value