cloudflarecloudflare-workerscloudflare-kv

Cloudflare worker scheduled response API KV


So previously I tried to store KV when CRON was processed and it works. Now I tried to store KV based on API responses, and tried the following: https://gist.github.com/viggy28/522c4ed05e2bec051d3838ebaff27258 and Forward body from request to another url for Scheduled (CRON workers) but doesn't seems to work.

What I attempt to do is save response in KV when CRON triggers for access_token and use it in front-end code later on.

Attached is my current attempt:

addEventListener("scheduled", (event) => {
    console.log("cron trigger processed..", event);
    event.waitUntil(handleRequest());
});

async function handleRequest() {
    const url = "<request_url>";
    const body = { <credential> };
    const init = {
        body: JSON.stringify(body),
        method: "POST",
        headers: {
            "content-type": "application/json;charset=UTF-8"
        }
    };
    const response = await fetch(url, init);
    const results = await gatherResponse(response);
    //@ts-ignore
    AUTH.put("attempt1", results);
    //@ts-ignore
    AUTH.put("attempt2", new Response(results, init));
    return new Response(results, init);
}

/**
 * gatherResponse awaits and returns a response body as a string.
 * Use await gatherResponse(..) in an async function to get the response body
 * @param {Response} response
 */
async function gatherResponse(response) {
  const { headers } = response
  const contentType = headers.get("content-type") || ""
  if (contentType.includes("application/json")) {
    return JSON.stringify(await response.json())
  }
  else if (contentType.includes("application/text")) {
    return await response.text()
  }
  else if (contentType.includes("text/html")) {
    return await response.text()
  }
  else {
    return await response.text()
  }
}

Both attempt doesn't seems to work (KV not saved):

    //@ts-ignore
    AUTH.put("attempt1", results);
    //@ts-ignore
    AUTH.put("attempt2", new Response(results, init));

Is there anything I'm missing?


Solution

  • The calls to NAMESPACE.put() return a Promise that should be awaited - I'd assume that since handleRequest() can return before those are completed (since you're missing the await), they're just being cancelled.

    https://developers.cloudflare.com/workers/runtime-apis/kv/#writing-key-value-pairs