使用 Neon 的無伺服器 Postgres 結合 Bun
Neon 是一個完全託管的無伺服器 Postgres。Neon 將計算和儲存分離,以提供自動擴縮容、分支和無限儲存等功能。
開始步驟:建立一個專案目錄,使用 bun init 初始化該目錄,並新增 Neon 無伺服器驅動 作為專案相依。
terminal
mkdir bun-neon-postgres
cd bun-neon-postgres
bun init -y
bun add @neondatabase/serverless
建立一個 .env.local 檔案,並將你的 Neon Postgres 連線字串 新增到其中。
.env.local
DATABASE_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.sh/docs/runtime/environment-variables 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 版本輸出到控制台。
terminal
bun ./index.ts
Text
PostgreSQL 16.2 on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit
此範例使用了 Neon 無伺服器驅動的基於 HTTP 的 SQL 功能。Neon 的無伺服器驅動還提供了 Client 和 Pool 建構函式,用於支援會話、互動式事務以及相容 node-postgres。
請參閱 Neon 的文件,瞭解無伺服器驅動的完整概覽。