Bun

指南生態系統

使用 Neon 的 Serverless Postgres 與 Bun

Neon 是一個完全管理的 Serverless Postgres。Neon 將運算和儲存分開,提供現代開發人員功能,例如自動調整大小、分支、無底儲存等等。

透過建立專案目錄、使用 bun init 初始化目錄,並將 Neon Serverless 驅動程式 加入專案相依性來開始使用。

mkdir bun-neon-postgres
cd bun-neon-postgres
bun init -y
bun add @neondatabase/serverless

建立一個 .env.local 檔案,並將您的 Neon Postgres 連線字串 加入其中。

DATBASE_URL=postgresql://username:password@ep-adj-noun-guid.us-east-1.aws.neon.tech/neondb?sslmode=require

將以下程式碼貼到專案的 index.ts 檔案中。

import { neon } from "@neondatabase/serverless";

// Bun automatically loads the DATABASE_URL from .env.local
// Refer to: https://bun.dev.org.tw/docs/runtime/env for more information
const sql = neon(process.env.DATABASE_URL);

const rows = await sql`SELECT version()`;

console.log(rows[0].version);

使用 bun ./index.ts 啟動程式。Postgres 版本應會印出至主控台。

bun ./index.ts
PostgreSQL 16.2 on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit

此範例使用 Neon Serverless 驅動程式的 SQL-over-HTTP 功能。Neon 的 Serverless 驅動程式也公開 ClientPool 建構函式,以啟用階段、互動式交易和與 node-postgres 相容。

請參閱 Neon 的文件,以取得 Serverless 驅動程式的完整概觀。