与 Supabase 数据库(Postgres)集成
Connect to your Postgres database from Edge Functions.
使用 supabase-js 客户端从 Edge Function 连接到你的 Postgres 数据库。你也可以使用其他 Postgres 客户端,比如 Deno Postgres
🌐 Connect to your Postgres database from an Edge Function by using the supabase-js client.
You can also use other Postgres clients like Deno Postgres
使用 supabase-js #
🌐 Using supabase-js
@supabase/server 的 withSupabase 封装器会给你一个已经根据调用者的行级安全策略配置好的 supabase-js 客户端(ctx.supabase),所以你不需要自己管理密钥或授权头。它还提供了 ctx.supabaseAdmin 用于绕过行级安全的高级操作。响应会自动格式化为 JSON。这是大多数应用推荐的方法:
🌐 The withSupabase wrapper from @supabase/server hands you a supabase-js client (ctx.supabase) already scoped to the caller's Row Level Security policies, so you don't manage keys or authorization headers yourself. It also provides ctx.supabaseAdmin for privileged operations that bypass Row Level Security. Responses are automatically formatted as JSON. This is the recommended approach for most applications:
1import { withSupabase } from 'npm:@supabase/server@^1'23export default {4 fetch: withSupabase({ auth: 'user' }, async (req, ctx) => {5 try {6 // ctx.supabase respects the caller's RLS policies.7 // ctx.supabaseAdmin bypasses RLS for privileged operations.8 const { data, error } = await ctx.supabase.from('countries').select('*')910 if (error) {11 throw error12 }1314 return Response.json({ data })15 } catch (err) {16 return Response.json({ error: String(err?.message ?? err) }, { status: 500 })17 }18 }),19}这使得:
🌐 This enables:
- 自动行级安全执行
- 内置 JSON 序列化
- 一致的错误处理
- TypeScript 对数据库模式的支持
使用 Postgres 客户端 #
🌐 Using a Postgres client
因为 Edge Functions 是服务器端技术,所以可以安全地使用任何流行的 Postgres 客户端直接连接到你的数据库。这意味着你可以从 Edge Functions 中运行原生 SQL。
🌐 Because Edge Functions are a server-side technology, it's safe to connect directly to your database using any popular Postgres client. This means you can run raw SQL from your Edge Functions.
这是如何使用 Deno Postgres 驱动连接到数据库并运行原生 SQL 的方法。查看完整示例吧。
🌐 Here is how you can connect to the database using Deno Postgres driver and run raw SQL. Check out the full example.
1import { Pool } from 'jsr:@db/postgres@^0'23// Create a database pool with one connection.4const pool = new Pool(Deno.env.get('SUPABASE_DB_URL')!, 1)56export default {7 fetch: async (_req) => {8 try {9 // Grab a connection from the pool10 const connection = await pool.connect()1112 try {13 // Run a query14 const result = await connection.queryObject`SELECT * FROM animals`15 const animals = result.rows // [{ id: 1, name: "Lion" }, ...]1617 const data = animals.map((animal) =>18 Object.fromEntries(19 Object.entries(animal).map(([key, value]) => [20 key,21 typeof value === 'bigint' ? value.toString() : value,22 ])23 )24 )2526 return Response.json(data, {27 headers: {28 'Content-Type': 'application/json; charset=utf-8',29 },30 })31 } finally {32 // Release the connection back into the pool33 connection.release()34 }35 } catch (err) {36 console.error(err)37 return Response.json({ error: String(err?.message ?? err) }, { status: 500 })38 }39 },40}使用 Drizzle #
🌐 Using Drizzle
你可以把 Drizzle 和 Postgres.js 一起使用。两者都可以直接从 npm 加载。
🌐 You can use Drizzle together with Postgres.js. Both can be loaded directly from npm.
在函数目录中的 deno.json 文件里声明依赖(更多详情请参见 管理函数依赖):
🌐 Declare the dependencies in a deno.json file inside the function directory (see Managing functions dependencies for more details):
1{2 "imports": {3 "drizzle-orm": "npm:drizzle-orm@0.29.1",4 "drizzle-orm/": "npm:/drizzle-orm@0.29.1/",5 "postgres": "npm:postgres@3.4.3"6 }7}然后定义你的模式并查询数据库:
🌐 Then define your schema and query the database:
1import { pgTable, serial, text, timestamp } from 'drizzle-orm/pg-core'23export const user = pgTable('user', {4 id: serial('id'),5 name: text('name'),6 email: text('email'),7 password: text('password'),8 role: text('role').$type<'admin' | 'customer'>(),9 createdAt: timestamp('created_at'),10 updatedAt: timestamp('updated_at'),11})1213export const countries = pgTable('countries', {14 id: serial('id'),15 name: text('name'),16})1import { drizzle } from 'npm:drizzle-orm@^0/postgres-js'2import postgres from 'npm:postgres@^3'34import { countries } from '../_shared/schema.ts'56const connectionString = Deno.env.get('SUPABASE_DB_URL')!7// Disable prefetch as it is not supported for "Transaction" pool mode8const client = postgres(connectionString, { prepare: false })9const db = drizzle(client)1011export default {12 fetch: async (_req) => {13 const allCountries = await db.select().from(countries)1415 return Response.json(allCountries)16 },17}你可以在 GitHub 上找到完整的示例。
🌐 You can find the full example on GitHub.
SSL 连接 #
🌐 SSL connections
生产 #
🌐 Production
已部署的边缘函数已经预先配置好使用 SSL 来连接 Supabase 数据库。你不需要添加任何额外的配置。
🌐 Deployed edge functions are pre-configured to use SSL for connections to the Supabase database. You don't need to add any extra configurations.
本地开发 #
🌐 Local development
如果你想在本地开发时使用 SSL 连接,请按照以下步骤操作:
🌐 If you want to use SSL connections during local development, follow these steps:
- 从 数据库设置 下载 SSL 证书
- 添加到你的本地 .env 文件,添加这两个变量:
1SSL_CERT_FILE=/path/to/cert.crt # set the path to the downloaded cert2DENO_TLS_CA_STORE=mozilla,system然后,重启你的本地开发服务器:
🌐 Then, restart your local development server:
1supabase functions serve your-function