N
Nuxt6mo ago
cosbgn

get `event` in `/utils/db.js` - Can I be done?

I would like to do something like this:
// utils/db.js
import { drizzle } from 'drizzle-orm/d1';
import * as schema_file from "../db/schema.js";

let cached_db = null

export const useDb = () => {
if (!cached_db) {
const event = useRequestEvent()
cached_db = drizzle(event.context.cloudflare.env.D1_PROD_BINDING, { schema: schema_file })
}
return cached_db
}

export const db = useDb()
export const schema = schema_file
// utils/db.js
import { drizzle } from 'drizzle-orm/d1';
import * as schema_file from "../db/schema.js";

let cached_db = null

export const useDb = () => {
if (!cached_db) {
const event = useRequestEvent()
cached_db = drizzle(event.context.cloudflare.env.D1_PROD_BINDING, { schema: schema_file })
}
return cached_db
}

export const db = useDb()
export const schema = schema_file
So then in any route I can do db.select() - However useRequestEvent() is not defined somehow? I know I can simply pass const db = useDb(event) on top of each route, I just would like to avoid passing event on every route and hopefully get better types. Should this instead be a plugin? What's the best practice here?
1 Reply
cosbgn
cosbgnOP5mo ago
Found it:
const binding = process?.env?.DB || globalThis?.__env__?.DB || globalThis?.DB
const db = drizzle(binding, { schema: schema_file })
const binding = process?.env?.DB || globalThis?.__env__?.DB || globalThis?.DB
const db = drizzle(binding, { schema: schema_file })
Want results from more Discord servers?
Add your server