跳至內容

Supabase 邊緣函式

Supabase 是 Firebase 的開源替代方案,提供類似 Firebase 功能的一套工具,包括資料庫、身份驗證、儲存以及現在的無伺服器函式。

Supabase 邊緣函式是全域分佈的伺服器端 TypeScript 函式,可在更靠近您使用者的地方執行,以提升效能。這些函式是使用 Deno 開發的,它帶來了多項優勢,包括更高的安全性以及現代化的 JavaScript/TypeScript 執行環境。

以下是如何開始使用 Supabase 邊緣函式的步驟:

1. 設定

先決條件

在開始之前,請確保您已安裝 Supabase CLI。如果您尚未安裝,請按照官方文件中的說明進行操作。

建立新專案

  1. 開啟您的終端機或命令提示字元。

  2. 在您本機上的目錄中執行以下命令,建立新的 Supabase 專案:

bash
supabase init

此命令會在目前目錄中初始化一個新的 Supabase 專案。

新增邊緣函式

  1. 在您的 Supabase 專案中,建立一個名為 hello-world 的新邊緣函式:
bash
supabase functions new hello-world

此命令會在您的專案中建立一個具有指定名稱的新邊緣函式。

2. Hello World

編輯 hello-world 函式,修改檔案 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. 執行

若要在本機執行函式,請使用以下命令:

  1. 使用以下命令來啟動函式:
bash
supabase start # start the supabase stack
supabase functions serve --no-verify-jwt # start the Functions watcher

--no-verify-jwt 標記可讓您在本機開發期間略過 JWT 驗證。

  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!"。

4. 部署

您可以使用單一命令,在 Supabase 中部署所有邊緣函式:

bash
supabase functions deploy

或者,您可以透過在部署命令中指定函式的名稱來部署個別的邊緣函式:

bash
supabase functions deploy hello-world

如需更多部署方法,請瀏覽 Supabase 關於部署至生產環境的文件。

根據 MIT 授權發布。