0

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?

Shinjo
  • 677
  • 6
  • 22
  • 1
    Is your script throwing an exception? Try viewing the live log while your cron trigger runs to see if there are any errors reported. https://developers.cloudflare.com/workers/learning/logging-workers/#view-logs-from-the-dashboard – Kenton Varda Feb 13 '23 at 15:37
  • Hi @KentonVarda, yes I'm getting Error in status. Is there anyway to check what make the cron errors? – Shinjo Feb 14 '23 at 03:14
  • 1
    Make sure you are watching the live log when the error happens. See my link above. It should show you the error details as long as you're watching in real time. (The logs aren't stored.) – Kenton Varda Feb 14 '23 at 17:14
  • Yeah, I've tried using realtime log but it doesn't have anything logged you can see [here](https://i.stack.imgur.com/K124x.png). As you can see in recent cron [image](https://i.stack.imgur.com/nlWKr.png) it was triggered in min 24. – Shinjo Feb 15 '23 at 01:30

1 Answers1

0

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

Kian
  • 116
  • 3
  • That's not the issue. As I wrote in OP "So previously I tried to store KV when CRON was processed and it works". Which means plain `NAMESPACE.put()` works without issue. My suspect was the API requests having some errors. – Shinjo Feb 14 '23 at 10:00
  • 1
    You *do* need to await the puts, otherwise they may or may not actually complete. It's possible they seem to work for HTTP handlers but the timing is different for cron. I suspect that your first `put()` is being canceled early since it wasn't awaited, and the second `put()` is throwing an exception because it's being given a `Response` object, which is not a valid type to store to KV. But, the error logs will say more. – Kenton Varda Feb 14 '23 at 17:18