Skip to content

Supabase 边缘函数

🌐 Supabase Edge Functions

Supabase 是 Firebase 的开源替代方案,提供类似于 Firebase 功能的一套工具,包括数据库、身份验证、存储,以及现在的无服务器函数。

Supabase Edge Functions 是在服务器端运行的 TypeScript 函数,全球分布,能够靠近用户运行以提高性能。这些函数是使用 Deno 开发的,它带来了多种好处,包括增强的安全性和现代化的 JavaScript/TypeScript 运行时。

🌐 Supabase Edge Functions are server-side TypeScript functions that are distributed globally, running closer to your users for improved performance. These functions are developed using Deno, which brings several benefits, including improved security and a modern JavaScript/TypeScript runtime.

以下是开始使用 Supabase Edge Functions 的方法:

🌐 Here's how you can get started with Supabase Edge Functions:

1. 设置

🌐 1. Setup

先决条件

🌐 Prerequisites

在开始之前,确保你已经安装了 Supabase CLI。如果你还没有安装,请按照官方文档中的说明进行操作。

🌐 Before you begin, make sure you have the Supabase CLI installed. If you haven't installed it yet, follow the instructions in the official documentation.

创建新的项目

🌐 Creating a New Project

  1. 打开你的终端或命令提示符。
  2. 通过运行以下命令在本地计算机的目录中创建一个新的 Supabase 项目:
bash
supabase init

此命令在当前目录中初始化一个新的 Supabase 项目。

🌐 This command initializes a new Supabase project in the current directory.

添加边缘函数

🌐 Adding an Edge Function

  1. 在你的 Supabase 项目中,创建一个名为 hello-world 的新 Edge Function:
bash
supabase functions new hello-world

此命令在你的项目中创建一个具有指定名称的新 Edge 函数。

🌐 This command creates a new Edge Function with the specified name in your project.

2. 你好,世界

🌐 2. Hello World

通过修改文件 supabase/functions/hello-world/index.ts 来编辑 hello-world 函数:

🌐 Edit the hello-world function by modifying the file supabase/functions/hello-world/index.ts:

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. 跑

🌐 3. Run

要在本地运行该函数,请使用以下命令:

🌐 To run the function locally, use the following command:

  1. 使用以下命令提供该功能:
bash
supabase start # start the supabase stack
supabase functions serve --no-verify-jwt # start the Functions watcher

--no-verify-jwt 标志允许你在本地开发期间绕过 JWT 验证。

🌐 The --no-verify-jwt flag allows you to bypass JWT verification during local development.

  1. 使用 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!”。

🌐 This request should return the text "Hello from hono-server!".

4. 部署

🌐 4. Deploy

你可以使用单个命令在 Supabase 中部署所有 Edge 函数:

🌐 You can deploy all of your Edge Functions in Supabase with a single command:

bash
supabase functions deploy

或者,你可以通过在部署命令中指定函数名称来部署单个边缘函数:

🌐 Alternatively, you can deploy individual Edge Functions by specifying the name of the function in the deploy command:

bash
supabase functions deploy hello-world

有关更多部署方法,请访问 Supabase 文档中的部署到生产环境

🌐 For more deployment methods, visit the Supabase documentation on Deploying to Production.

Hono 中文网 - 粤ICP备13048890号