Skip to content

Commit

Permalink
chore: up
Browse files Browse the repository at this point in the history
  • Loading branch information
atinux committed Jan 26, 2024
1 parent ef38aa0 commit 7728586
Show file tree
Hide file tree
Showing 14 changed files with 139 additions and 84 deletions.
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,3 @@ dist
.netlify
db.sqlite-*
.hub
.wrangler/state/v3
42 changes: 0 additions & 42 deletions _nuxthub/modules/hub.ts

This file was deleted.

72 changes: 72 additions & 0 deletions _nuxthub/modules/hub/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { defineNuxtModule, createResolver } from 'nuxt/kit'
import { join } from 'pathe'
import { defu } from 'defu'
import { mkdir, writeFile, readFile } from 'node:fs/promises'

export default defineNuxtModule({
meta: {
name: 'hub'
},
async setup (_options, nuxt) {
const { resolve } = createResolver(import.meta.url)

// Add Server utils based on environment
// nuxt.options.nitro.imports = nuxt.options.nitro.imports || {}
// nuxt.options.nitro.imports.dirs = nuxt.options.nitro.imports.dirs || []
// nuxt.options.nitro.imports.dirs.push(resolve(`../server/_utils/${nuxt.options.dev ? 'dev' : 'prod'}/`))

// Production mode
if (!nuxt.options.dev) {
return
}

if (process.env.NUXT_HUB_URL) {
// TODO: check on hub.nuxt.com if the project is connected
// return
// return once we support Proxy for all providers (R2 missing now)
}

// Local development without remote connection
// Create the .hub/ directory
const hubDir = join(nuxt.options.rootDir, './.hub')
try {
await mkdir(hubDir)
} catch (e: any) {
if (e.errno === -17) {
// File already exists
} else {
throw e
}
}
// Add it to .gitignore
const gitignorePath = join(nuxt.options.rootDir, './.gitignore')
const gitignore = await readFile(gitignorePath, 'utf-8')
if (!gitignore.includes('.hub')) {
await writeFile(gitignorePath, gitignore + '\n.hub', 'utf-8')
}

// Generate the wrangler.toml file
const wranglerPath = join(hubDir, './wrangler.toml')
await writeFile(wranglerPath, DEFAULT_WRANGLER, 'utf-8')
nuxt.options.runtimeConfig.wrangler = defu(nuxt.options.runtimeConfig.wrangler, {
configPath: wranglerPath,
persistDir: hubDir
})
// Make sure runtime is transpiled
// nuxt.options.nitro.externals.inline = nuxt.options.nitro.externals.inline || []
// nuxt.options.nitro.externals.inline.push(resolve('./runtime/server'))
// Add server plugin
nuxt.options.nitro.plugins = nuxt.options.nitro.plugins || []
nuxt.options.nitro.plugins.push(resolve('./runtime/server/plugins/cloudflare.dev'))
}
})

const DEFAULT_WRANGLER = `d1_databases = [
{ binding = "DB", database_name = "default", database_id = "default" },
]
kv_namespaces = [
{ binding = "KV", id = "default" },
]
r2_buckets = [
{ binding = "BUCKET", bucket_name = "default" },
]`
52 changes: 52 additions & 0 deletions _nuxthub/modules/hub/runtime/server/plugins/cloudflare.dev.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import type { NitroAppPlugin } from 'nitropack'
// @ts-ignore
import { useRuntimeConfig } from '#imports'

export default <NitroAppPlugin>function (nitroApp) {
let _proxy: ReturnType<typeof 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() }
})
}

// 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,
}
})

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

async function getBindingsProxy() {
const _pkg = 'wrangler' // Bypass bundling!
const { getBindingsProxy } = (await import(
_pkg
)) as typeof import('wrangler')

const runtimeConfig: {
wrangler: { configPath: string; persistDir: string };
} = useRuntimeConfig()

const proxy = await getBindingsProxy({
configPath: runtimeConfig.wrangler.configPath,
persist: { path: runtimeConfig.wrangler.persistDir },
})

return proxy
}
1 change: 0 additions & 1 deletion _nuxthub/nuxt.config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
export default defineNuxtConfig({
// ./modules are autoloaded
modules: ['nitro-cloudflare-dev']
})
18 changes: 6 additions & 12 deletions _nuxthub/server/utils/bucket.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,22 @@
import type { H3Event } from 'h3'
import type { R2Bucket } from '@cloudflare/workers-types/experimental'

const _buckets: Record<string, R2Bucket> = {}

export function useBucket (event: H3Event, name: string = '') {
export function useBucket (name: string = '') {
const bucketName = name ? `BUCKET_${name.toUpperCase()}` : 'BUCKET'
if (_buckets[bucketName]) {
return _buckets[bucketName]
}

if (process.env.NUXT_HUB_URL) {
console.log('Using local bucket as proxy for useBucket() is not yet supported')
console.log('Using R2 local (proxy for useBucket() is not yet supported)')
}

// TODO: move to globalThis.__env__ or process.env
const cfEnv = event.context.cloudflare?.env
if (!cfEnv) {
console.log(event.context.cloudflare)
throw createError('Missing Cloudflare env')
}
if (!cfEnv[bucketName]) {
// @ts-ignore
const binding = globalThis[bucketName]
if (!binding) {
throw createError(`Missing Cloudflare R2 binding ${bucketName}`)
}
_buckets[bucketName] = cfEnv[bucketName] as R2Bucket
_buckets[bucketName] = binding as R2Bucket

return _buckets[bucketName]
}
2 changes: 1 addition & 1 deletion _nuxthub/server/utils/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export function useDatabase () {
})
} else if (import.meta.dev) {
// local sqlite in development
console.log('Using local database...')
console.log('Using D1 local database...')
_client = new Database(join(process.cwd(), './.hub/db.sqlite'))
_db = drizzle(_client)
} else {
Expand Down
4 changes: 2 additions & 2 deletions _nuxthub/server/utils/kv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export function useKV (prefix?: string) {
})
})
} else if (import.meta.dev && process.env.NUXT_HUB_URL) {
console.log('Using remote KV...')
console.log('Using remote KV namespace...')
// Use https://unstorage.unjs.io/drivers/http
_kv = createStorage({
driver: httpDriver({
Expand All @@ -30,7 +30,7 @@ export function useKV (prefix?: string) {
})
} else if (import.meta.dev) {
// local kv in development
console.log('Using local KV...')
console.log('Using local KV namespace...')
_kv = createStorage({
driver: fsDriver({ base: join(process.cwd(), './.hub/kv') })
})
Expand Down
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
"drizzle-kit": "^0.20.13",
"drizzle-orm": "^0.29.3",
"h3-zod": "^0.5.3",
"nitro-cloudflare-dev": "^0.0.7",
"nuxt": "^3.9.3",
"nuxt-auth-utils": "^0.0.14",
"utf-8-validate": "^6.0.3",
Expand Down
2 changes: 1 addition & 1 deletion pages/storage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ const items = [[{
:key="index"
class="flex items-center gap-4 py-2"
>
<span class="flex-1 font-medium">{{ file }}</span>
<span class="flex-1 font-medium">{{ file.key }}</span>
</li>
</ul>
</UCard>
Expand Down
10 changes: 0 additions & 10 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion server/api/bucket-test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { R2ListOptions } from '@cloudflare/workers-types/experimental'

export default eventHandler(async (event) => {
const bucket = useBucket(event)
const bucket = useBucket()

await bucket.put('test2.txt', 'Hello World!', {
httpMetadata: {
Expand Down
7 changes: 4 additions & 3 deletions server/api/storage/index.get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,16 @@ export default eventHandler(async (event) => {
const session = await requireUserSession(event)

// List files for the current user
const storage = await useBucket(event)

console.log('storage', storage)
const res = await useBucket().list()

return res.objects

// const keys = await storage.getKeys()
// // const items = await storage.getItems(keys)
// const items = await Promise.all(keys.map(async (key) => {
// const value = await storage.getItem(key)
// return { path: key, content: value }
// }))
return []
// return []
})
9 changes: 0 additions & 9 deletions wrangler.toml

This file was deleted.

0 comments on commit 7728586

Please sign in to comment.