Access D1 database outside a request
Hello,
I am trying to configure a D1 database for my Cloudflare worker. I have already created the database and added it to . In the docs (https://developers.cloudflare.com/d1/get-started/), they say we can access the database like this:
Well, that's great, but how can I read the database content within a function which is not related to a request and does not have a prebuilt parameter?
15 Replies
You don't. All external I/O must be performed in the context of a Request(or other event)
So I guess that it could be performed for a cron trigger event?
Yup, HTTP Events, Cron Triggers, Queues, Emails, etc. are all valid event types that give you access to I/O
Thank you for your clarifications. It is also likely that itty router provides access to the database by responding to a request, isn't it?
Sure, I believe there is a way to pass bindings around with
itty
ok, thank you!
Hey, sorry if this is unrelated but doesn’t cloud flare offer a rest api for D1 requests? https://developers.cloudflare.com/api/operations/cloudflare-d1-create-database Unsure if this could help 😅
Cloudflare API Documentation
Interact with Cloudflare's products and services via the Cloudflare API
I don't see a directly example of itty router with cloudflare in their repository, but Hono, similar to itty router, has direct support for bindings: https://hono.dev/docs/getting-started/cloudflare-workers#bindings
Cloudflare Workers - Hono
Ultrafast web framework for Cloudflare Workers, Fastly Compute, Deno, Bun, Vercel, Node.js, and others. Fast, but not only fast.
Yes, but you still can't do I/O outside of the Request context. This includes the
fetch
calls which you would need for that APIOh right my bad 😅
You can create a middleware that you set a d1 clousure instance and use it without passing context.d1 to your functions that need dababase:
ex:
the middleware before all req could be like that:
to use
this is a very interesting solution, I will make sure to try it out
thank you!
Do you use Hono with cloudflare workers, right?
Do u can help with that:
https://discord.com/channels/595317990191398933/1276333679907704984/1276333679907704984
I am sorry, I am using itty-router with my worker
However I also encounter some issues with cors
Bindings are just passed along automatically in the 2nd/
env
argument to handlers/middleware, if you wired things up manually, you'll need to feed it in yourself, but if you just use the default fetch signature, it'll pick up all the cloudflare args and pass them along (env and context).
Basically, itty (platform agnostic) allows you to pass anything throughout the entire handler/middleware chain just by passing it to the router.fetch
function after the Request
object. Cloudflare calls the { fetch }
function with these args, so you automatically see them in itty handlers!