Skip to content

Commit

Permalink
chore: up
Browse files Browse the repository at this point in the history
  • Loading branch information
atinux committed Feb 5, 2024
1 parent 3cfc682 commit dcd1e38
Show file tree
Hide file tree
Showing 13 changed files with 90 additions and 607 deletions.
39 changes: 17 additions & 22 deletions _nuxthub/modules/hub/runtime/server/plugins/cloudflare.dev.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,23 @@
import type { NitroAppPlugin } from 'nitropack'
// @ts-ignore
import { useRuntimeConfig } from '#imports'
import { defineNitroPlugin, useRuntimeConfig } from '#imports'

export default <NitroAppPlugin>function (nitroApp) {
let _proxy: ReturnType<typeof getBindingsProxy>
export default defineNitroPlugin(async (nitroApp) => {
const proxyPromise = getBindingsProxy()

nitroApp.hooks.hook('request', async (event) => {
// Lazy initialize proxy when first request comes in
if (!_proxy) {
_proxy = getBindingsProxy().catch((error) => {
console.error('Failed to initialize wrangler bindings proxy', error)
return { bindings: {}, dispose: () => Promise.resolve() }
})
}

const proxy = await proxyPromise
// Inject proxy bindings to the request context
const bindings = (await _proxy).bindings
Object.keys(bindings).forEach((key) => {
if (!globalThis[key]) {
globalThis[key] = bindings[key]
}
})
event.context.cloudflare = {
...event.context.cloudflare,
env: bindings,
env: proxy.bindings,
}
})

// Dispose proxy when Nitro is closed
nitroApp.hooks.hook('close', () => {
return _proxy?.then((proxy) => proxy.dispose)
return proxyPromise.then((proxy) => proxy.dispose())
})
}
})

async function getBindingsProxy() {
const _pkg = 'wrangler' // Bypass bundling!
Expand All @@ -48,5 +34,14 @@ async function getBindingsProxy() {
persist: { path: runtimeConfig.wrangler.persistDir },
})

Object.keys(proxy.bindings).forEach((key) => {
if (!globalThis[key]) {
globalThis[key] = proxy.bindings[key]
}
})

// @ts-ignore
await hubHooks.callHook('bindings:ready')

return proxy
}
}
20 changes: 0 additions & 20 deletions _nuxthub/server/api/_hub/database/query.post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,6 @@ export default eventHandler(async (event) => {
// Make sure the client is initialized first
const client = useDatabaseClient()

if (process.dev) {
try {
if (method === 'run')
return client.prepare(sql).run(params)
if (method === 'all' || method === 'values')
return client.prepare(sql).raw().all(params)
// method = 'get'
return client.prepare(sql).raw().get(params)
} catch (e: any) {
throw createError({
statusCode: 500,
message: `Database error: ${e.message}`
})
}
}

// await verifyHubSecretKey(event)
// TODO: Validate header for authorization through hub.nuxt.com
// const [, secretKey] = (getHeader(event, 'authorization') || '').split(' ')

try {
if (method === 'run') {
const { meta } = await client.prepare(sql).bind(...params).run()
Expand Down
3 changes: 3 additions & 0 deletions _nuxthub/server/utils/blob.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,10 @@ export function useBlob () {
const proxyURL = import.meta.dev && process.env.NUXT_HUB_URL
let bucket: R2Bucket
if (!proxyURL) {
import.meta.dev && console.log('Using Blob local storage...')
bucket = _useBucket()
} else {
import.meta.dev && console.log('Using Blob remote storage...')
}

return {
Expand Down
25 changes: 12 additions & 13 deletions _nuxthub/server/utils/database.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { D1Database } from '@cloudflare/workers-types/experimental'
import { drizzle as drizzleD1, DrizzleD1Database } from 'drizzle-orm/d1'
import { drizzle } from 'drizzle-orm/better-sqlite3'
import type { BetterSQLite3Database } from 'drizzle-orm/better-sqlite3'
Expand All @@ -10,16 +11,12 @@ import { join } from 'pathe'

export * as tables from '~/server/database/schema'

let _db: DrizzleD1Database | BetterSQLite3Database | SqliteRemoteDatabase | null = null
let _client: any = null
let _db: DrizzleD1Database | BetterSQLite3Database | SqliteRemoteDatabase
let _client: D1Database

export function useDatabase () {
if (!_db) {
if (process.env.DB) {
// d1 in production
_client = process.env.DB
_db = drizzleD1(_client)
} else if (import.meta.dev && process.env.NUXT_HUB_URL) {
if (import.meta.dev && process.env.NUXT_HUB_URL) {
console.log('Using D1 remote database...')
_db = drizzleHTTP(async (sql, params, method) => {
// https://orm.drizzle.team/docs/get-started-sqlite#http-proxy
Expand All @@ -42,13 +39,15 @@ export function useDatabase () {
return { rows: [] }
}
})
} else if (import.meta.dev) {
// local sqlite in development
console.log('Using D1 local database...')
_client = new Database(join(process.cwd(), './.hub/db.sqlite'))
_db = drizzle(_client)
} else {
throw new Error('No database configured for production')
const binding = process.env.DB || globalThis.__env__?.DB || globalThis.DB
if (binding) {
_client = binding as D1Database
_db = drizzleD1(_client)
import.meta.dev && console.log('Using D1 local database...')
} else {
throw createError('Missing Cloudflare D1 binding DB')
}
}
}
return _db
Expand Down
14 changes: 14 additions & 0 deletions _nuxthub/server/utils/hooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { createHooks } from 'hookable'

export interface HubHooks {
'bindings:ready': () => any | void
}

export const hubHooks = createHooks<HubHooks>()

export function onHubReady (cb: HubHooks['bindings:ready']) {
if (import.meta.dev) {
return hubHooks.hookOnce('bindings:ready', cb)
}
cb()
}
5 changes: 3 additions & 2 deletions _nuxthub/server/utils/kv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ let _kv: Storage

export function useKV () {
if (!_kv) {
// TODO: same as database
if (process.env.KV) {
// kv in production
_kv = createStorage({
Expand All @@ -18,7 +19,7 @@ export function useKV () {
})
})
} else if (import.meta.dev && process.env.NUXT_HUB_URL) {
console.log('Using remote KV namespace...')
console.log('Using KV remote namespace...')
// Use https://unstorage.unjs.io/drivers/http
_kv = createStorage({
driver: httpDriver({
Expand All @@ -30,7 +31,7 @@ export function useKV () {
})
} else if (import.meta.dev) {
// local kv in development
console.log('Using local KV namespace...')
console.log('Using KV local namespace...')
_kv = createStorage({
driver: fsDriver({ base: join(process.cwd(), './.hub/kv') })
})
Expand Down
11 changes: 0 additions & 11 deletions drizzle.config.ts

This file was deleted.

5 changes: 1 addition & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
"dev": "nuxi dev",
"build": "nuxi build --preset cloudflare_pages",
"preview": "nuxt preview",
"migrate": "drizzle-kit generate:sqlite",
"lint": "eslint .",
"postinstall": "nuxt prepare",
"logs": "wrangler pages deployment tail"
Expand All @@ -16,16 +15,14 @@
"@iconify-json/simple-icons": "^1.1.90",
"@libsql/client": "^0.4.3",
"@nuxt/ui": "^2.13.0",
"better-sqlite3": "^9.3.0",
"bufferutil": "^4.0.8",
"drizzle-kit": "^0.20.13",
"drizzle-orm": "^0.29.3",
"image-meta": "^0.2.0",
"mime": "^4.0.1",
"nuxt": "^3.10.0",
"nuxt-auth-utils": "^0.0.15",
"utf-8-validate": "^6.0.3",
"wrangler": "^3.25.0",
"wrangler": "^3.26.0",
"zod": "^3.22.4"
},
"devDependencies": {
Expand Down
Loading

0 comments on commit dcd1e38

Please sign in to comment.