nuxt-hub / core

Build full-stack applications with Nuxt on CloudFlare, with zero configuration.
https://hub.nuxt.com
Apache License 2.0
937 stars 53 forks source link

feat: add support for extra bindings (Hyperdrive) #245

Closed atinux closed 1 month ago

atinux commented 1 month ago

Resolves #208

We can specify extra bindings that will be added when deploying the project (without having to use a wrangler.toml)

So far I want to experience using bindings.hyperdrive before thinking of a hyperdrive key as the remote storage might be tricky to handle.

Example:

export default defineNuxtConfig({
  hub: {
    bindings: {
      hyperdrive: {
        // tip: use an environment variable here instead
        POSTGRES: '08f7bc805d1d409aac17e72af502abd0'
      }
    }
  }
})

Then in your API route:

import type { Hyperdrive } from '@cloudflare/workers-types'
import postgres from 'postgres'

export default eventHandler(async (event) => {
  // Check if hyperdrive is available (only on Cloudflare)
  const hyperdrive = process.env.POSTGRES as Hyperdrive | undefined
  // Fallback to local Postgres DB URL
  const dbURL = hyperdrive?.connectionString || process.env.NUXT_POSTGRES_URL

  const sql = postgres(dbURL, {
    ssl: import.meta.dev ? 'require' : false // hyperdrive should not use ssl for now
  })

  const products = await sql`SELECT * FROM products`

  event.waitUntil(sql.end())
  return products
})

I plan to have a top-level hub.hyperdrive property and support hubHyperdrive() but so far it seems that the platform proxy from wrangler does not support hyperdrive right now, so I will open another PR once this will be possible.

pkg-pr-new[bot] commented 1 month ago

commit: 65887f9

pnpm add https://pkg.pr.new/nuxt-hub/core/@nuxthub/core@245

Open in Stackblitz

cloudflare-workers-and-pages[bot] commented 1 month ago

Deploying nuxthub-docs with  Cloudflare Pages  Cloudflare Pages

Latest commit: 65887f9
Status: ✅  Deploy successful!
Preview URL: https://1774ce49.nuxthub-module.pages.dev
Branch Preview URL: https://feat-hyperdrive.nuxthub-module.pages.dev

View logs