Supabase Edge Functions
Supabase 是一个开源的 Firebase 替代方案,提供与 Firebase 类似的一整套工具,包括数据库、身份验证、存储,以及现在的无服务器(serverless)函数。
Supabase Edge Functions 是分布式的 TypeScript 服务器端函数,可以在更靠近用户的位置运行,从而提升性能。这些函数基于 Deno 运行,具备多种优势,包括更高的安全性以及现代化的 JavaScript/TypeScript 运行时。
以下是如何开始使用 Supabase Edge Functions:
1. 设置
前置条件
在开始之前,请确保已经安装了 Supabase CLI。如果还没有安装,请参考 官方文档。
创建新项目
- 打开终端或命令行窗口。
- 在本地目录中运行以下命令创建一个新的 Supabase 项目:
supabase init
此命令会在当前目录中初始化一个新的 Supabase 项目。
添加 Edge Function
- 在 Supabase 项目中创建一个名为
hello-world
的 Edge Function:
supabase functions new hello-world
该命令会在项目中创建一个指定名称的 Edge Function。
2. Hello World
编辑 hello-world
函数,修改 supabase/functions/hello-world/index.ts
文件:
import { Hono } from 'jsr:@hono/hono'
// 修改为你的函数名称
const functionName = 'hello-world'
const app = new Hono().basePath(`/${functionName}`)
app.get('/hello', (c) => c.text('Hello from hono-server!'))
Deno.serve(app.fetch)
3. 运行
要在本地运行函数,请使用以下命令:
- 启动 Supabase stack 并启动 Functions 监听服务:
supabase start # 启动 supabase stack
supabase functions serve --no-verify-jwt # 启动 Functions watcher
--no-verify-jwt
参数允许在本地开发时跳过 JWT 验证。
- 使用 cURL 或 Postman 发送 GET 请求到
http://127.0.0.1:54321/functions/v1/hello-world/hello
:
curl --location 'http://127.0.0.1:54321/functions/v1/hello-world/hello'
该请求应返回文本 “Hello from hono-server!”。
4. 部署
你可以通过一条命令部署所有 Supabase Edge Functions:
supabase functions deploy
也可以指定函数名称部署单个 Edge Function:
supabase functions deploy hello-world
更多部署方法,请参考 Supabase 官方文档 Deploying to Production。