Hi, I'm using QwikCity deployed to Cloudflare Pages, connecting to PlanetScale using the Drizzle ORM.
I've wrote this code to handle connecting to the database:
// utils/db.ts
import { drizzle } from "drizzle-orm/planetscale-serverless";
import { connect } from "@planetscale/database";
import type { Connection } from "@planetscale/database";
import * as schema from "~/../drizzle/schema";
import type { EnvGetter } from "@builder.io/qwik-city/middleware/request-handler";
/* eslint-disable no-var */
declare global {
var __connection: Connection | undefined;
var __drizzle: ReturnType<typeof drizzle<typeof schema>> | undefined;
}
/* eslint-enable no-var */
export const getDb = (envOrUrl: EnvGetter | string | undefined) => {
if (!globalThis.__connection)
globalThis.__connection = connect({
url: envOrUrl
? typeof envOrUrl === "string"
? envOrUrl
: envOrUrl.get("DB_URL")
: undefined,
fetch: (url: string, init?: RequestInit) => {
if (init) delete init["cache"];
return fetch(url, init);
},
});
if (!globalThis.__drizzle)
globalThis.__drizzle = drizzle(globalThis.__connection, { schema });
return globalThis.__drizzle;
};
This means, that in every server-side function I can call getDb(env) to get the database instance.
I just have two questions:
- Will the connection be reinitialized every time
getDbis called in the same worker? - Is it possible to refactor this code, such so the
envdoesn't have to get passed, and I can just export a variable? I can't just useprocess.env, as that's not available on Cloudflare.
