Instantiate a connection with PlanetScale in Cloudflare Workers

Hey, What would be the right way to instantiate a database connection with PlanetScale in Cloudflare workers and reuse it across different handlers? We cannot instantiate it outside the handler because we have no access to the environment variables :
const connection = connect({
url: ENV,
fetch: (url, init) => {
delete init["cache"];
return fetch(url, init);
},
});

const db = drizzle(connection);

app.get("/users", async () => ...);
const connection = connect({
url: ENV,
fetch: (url, init) => {
delete init["cache"];
return fetch(url, init);
},
});

const db = drizzle(connection);

app.get("/users", async () => ...);
So, we need to create a function where we can pass the env object as a parameter to access the environment variables:
export function db(env: ENV_VARIABLES) {
const connection = connect({
url: env.DATABASE_URL,
fetch: (url, init) => {
delete init["cache"];
return fetch(url, init);
},
});

return drizzle(connection);
}
export function db(env: ENV_VARIABLES) {
const connection = connect({
url: env.DATABASE_URL,
fetch: (url, init) => {
delete init["cache"];
return fetch(url, init);
},
});

return drizzle(connection);
}
And then use it in different handlers:
app.post("/users", async (context) => db.insert(users).values({...});
app.post("/posts", async (context) => db.insert(posts).values({...});
app.post("/users", async (context) => db.insert(users).values({...});
app.post("/posts", async (context) => db.insert(posts).values({...});
I wonder if this is a safe way to instantiate a connection and reuse it across different handlers with Cloudflare Workers?
1 Reply
Andrii Sherman
Andrii Sherman15mo ago
It's fine I guess. You can also have some sort of singleton pattern for that
Want results from more Discord servers?
Add your server