Unverified Commit 89970e8d authored by Hong Minhee's avatar Hong Minhee
Browse files

Refactor WorkersKvStore.list() to use single loop

Extract pattern and exactKey before the conditional logic, then use
a unified listing loop.

https://github.com/fedify-dev/fedify/pull/500#discussion_r2641821957



Co-Authored-By: default avatarClaude <noreply@anthropic.com>
parent b88e3de1
Loading
Loading
Loading
Loading
+34 −52
Original line number Diff line number Diff line
@@ -90,40 +90,22 @@ export class WorkersKvStore implements KvStore {
   * @since 1.10.0
   */
  async *list(prefix?: KvKey): AsyncIterable<KvStoreListEntry> {
    let pattern: string;
    let exactKey: string | null = null;

    if (prefix == null || prefix.length === 0) {
      // Empty prefix: list all entries
      // JSON encoded keys start with '[', so prefix with '[' to match all arrays
      let cursor: string | undefined;
      do {
        const result = await this.#namespace.list<KvMetadata>({
          prefix: "[",
          cursor,
        });
        cursor = result.list_complete ? undefined : result.cursor;

        for (const keyInfo of result.keys) {
          const metadata = keyInfo.metadata as KvMetadata | undefined;
          if (metadata?.expires != null && metadata.expires < Date.now()) {
            continue;
          }

          const value = await this.#namespace.get(keyInfo.name, "json");
          if (value == null) continue;

          yield {
            key: JSON.parse(keyInfo.name) as KvKey,
            value,
          };
        }
      } while (cursor != null);
      pattern = "[";
    } else {
      // Keys are JSON encoded: '["prefix","a"]'
      // Pattern to match keys starting with prefix: '["prefix",' matches children
      // Also check for exact match: '["prefix"]'
      const exactKey = this.#encodeKey(prefix);
      const childrenPattern = JSON.stringify(prefix).slice(0, -1) + ",";
      exactKey = this.#encodeKey(prefix);
      pattern = JSON.stringify(prefix).slice(0, -1) + ",";
    }

    // First, check if the exact prefix key exists
    if (exactKey != null) {
      const { value, metadata } = await this.#namespace.getWithMetadata(
        exactKey,
        "json",
@@ -134,16 +116,17 @@ export class WorkersKvStore implements KvStore {
          (metadata as KvMetadata).expires! >= Date.now())
      ) {
        yield {
          key: prefix,
          key: prefix!,
          value,
        };
      }
    }

      // Then list all keys starting with prefix
    // List all keys matching the pattern
    let cursor: string | undefined;
    do {
      const result = await this.#namespace.list<KvMetadata>({
          prefix: childrenPattern,
        prefix: pattern,
        cursor,
      });
      cursor = result.list_complete ? undefined : result.cursor;
@@ -165,7 +148,6 @@ export class WorkersKvStore implements KvStore {
    } while (cursor != null);
  }
}
}

/**
 * Implementation of the {@link MessageQueue} interface for Cloudflare