Skip to content

Commit e618923

Browse files
authored
feat(db): support Nitro useDatabase() (#15)
1 parent 824c998 commit e618923

File tree

5 files changed

+38
-0
lines changed

5 files changed

+38
-0
lines changed

playground/nuxt.config.ts

+1
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ export default defineNuxtConfig({
2525
nitro: {
2626
// preset: 'cloudflare-durable',
2727
experimental: {
28+
database: true,
2829
openAPI: true,
2930
websocket: true
3031
}
File renamed without changes.

playground/server/api/db-test.ts playground/server/api/tests/db.ts

+14
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,20 @@
11
import { sqliteTable, integer, text } from 'drizzle-orm/sqlite-core'
22

33
export default defineEventHandler(async () => {
4+
const db0 = useDatabase()
5+
6+
const _tables = await db0.sql`
7+
SELECT
8+
name,
9+
type
10+
FROM
11+
sqlite_schema
12+
WHERE
13+
type = 'table' AND
14+
name NOT LIKE 'sqlite_%' and name NOT LIKE '_litestream_%' and name NOT LIKE '__drizzle%'
15+
;`
16+
17+
console.log(_tables.rows)
418
const db = useDrizzle()
519

620
const tables = await db.all(sql`

playground/server/api/tests/kv.ts

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
export default eventHandler(async () => {
2+
const kv = hubKV()
3+
4+
await kv.set('vue', { year: 2014 })
5+
await kv.set('vue:nuxt', { year: 2016 })
6+
await kv.set('vue:quasar', { version: 2015 })
7+
await kv.set('react', { version: 2013 })
8+
await kv.set('react:next', { version: 2016 })
9+
await kv.set('react:gatsby', { version: 2015 })
10+
11+
return kv.keys()
12+
})

src/features.ts

+11
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,17 @@ export async function setupDatabase(nuxt: Nuxt, hub: HubConfig) {
216216
// Add Server scanning
217217
addServerScanDir(resolve('./runtime/database/server'))
218218
addServerImportsDir(resolve('./runtime/database/server/utils'))
219+
// Bind `useDatabase()` to `hubDatabase()` if experimental.database is true
220+
if (nuxt.options.nitro.experimental?.database) {
221+
// @ts-expect-error cannot respect the typed database configs
222+
nuxt.options.nitro.database = defu(nuxt.options.nitro.database, {
223+
default: {
224+
connector: 'cloudflare-d1',
225+
options: { bindingName: 'DB' }
226+
}
227+
})
228+
}
229+
// Handle migrations
219230
nuxt.hook('modules:done', async () => {
220231
// Call hub:database:migrations:dirs hook
221232
await nuxt.callHook('hub:database:migrations:dirs', hub.databaseMigrationsDirs!)

0 commit comments

Comments
 (0)