Bun

指南生態系統

搭配 Bun 使用 Neon 的無伺服器 Postgres

Neon 是一個完全託管的無伺服器 Postgres。Neon 分離了運算和儲存,以提供現代開發人員功能,例如自動擴展、分支、無限儲存等等。

首先,建立一個專案目錄,使用 bun init 初始化目錄,並新增 Neon 無伺服器驅動程式 作為專案依賴。

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

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

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.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 無伺服器驅動程式的 SQL-over-HTTP 功能。Neon 的無伺服器驅動程式也公開了 ClientPool 建構函式,以啟用工作階段、互動式交易和 node-postgres 相容性。

請參閱 Neon 的文件,以獲得無伺服器驅動程式的完整概述。