Supabase Edge Functions
Supabase 是 Firebase 的开源替代方案,提供与 Firebase 类似的一整套工具,包括数据库、身份验证、存储,以及现在支持的无服务器函数。
Supabase Edge Functions 是全球分布的服务端 TypeScript 函数,在更靠近用户的位置运行,以提高性能。这些函数使用 Deno 开发,具有更好的安全性以及现代 JavaScript/TypeScript 运行时等优点。
下面介绍如何开始使用 Supabase Edge Functions:
1. 初始化
前提条件
开始前,请确保已安装 Supabase CLI。如果尚未安装,请按照官方文档的说明操作。
创建新项目
打开终端或命令提示符。
运行以下命令,在本地计算机的目录中创建新的 Supabase 项目:
bash
supabase init此命令会在当前目录中初始化新的 Supabase 项目。
添加 Edge Function
- 在 Supabase 项目中创建一个名为
hello-world的新 Edge Function:
bash
supabase functions new hello-world此命令会在项目中创建指定名称的新 Edge Function。
2. Hello World
修改文件 supabase/functions/hello-world/index.ts,以编辑 hello-world 函数:
ts
import { Hono } from 'jsr:@hono/hono'
// change this to your function name
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. 运行
要在本地运行函数,请使用以下命令:
- 使用以下命令启动函数服务:
bash
supabase start # start the supabase stack
supabase functions serve --no-verify-jwt # start the Functions watcher--no-verify-jwt 标志允许在本地开发期间跳过 JWT 验证。
- 使用 cURL 或 Postman 向
http://127.0.0.1:54321/functions/v1/hello-world/hello发送 GET 请求:
bash
curl --location 'http://127.0.0.1:54321/functions/v1/hello-world/hello'此请求应返回文本「Hello from hono-server!」。
4. 部署
只需一个命令,即可部署 Supabase 中的全部 Edge Functions:
bash
supabase functions deploy也可以在部署命令中指定函数名称,以单独部署 Edge Function:
bash
supabase functions deploy hello-world更多部署方法请参阅 Supabase 文档中的部署到生产环境。