Yes, I’ve switched to using a worker to write to KV, but I see there’s no bulk write support. How ca

Yes, I’ve switched to using a worker to write to KV, but I see there’s no bulk write support. How can I write to KV concurrently from a worker? My code currently looks like
async function putKeys(env: Env, pairs: Array<Record<string, string>>): Promise<Response> {
  for (const pair of pairs) {
    var lastE = null;

    for (let i = 0; i < retries; i++) {
      try {
        await env.KV_NS.put(pair["key"], pair["value"], {
          metadata: {
            version: "v1",
            timestamp: ((Date.now() / 1000) | 0)
          }
        });
        console.log({"message": `Successful to sync key ${pair["key"]}`});
        break;
      } catch(e) {
        lastE = e;
      }
    }

    if (lastE != null) {
      console.error({"message": `Failed to sync key ${pair["key"]}`, error: lastE});
    }
  }
  console.log({"message": `Successful synced ${pairs.length} pairs`});

  return new Response(null, {});
}
Was this page helpful?