私有部署supabase完整手册-3 边函数(Edge Functions)开发/部署/测试

搭建本地supabase cli 开发环境

环境准备

提前准备好windos11/ node / docker 桌面环境.

docker安装之后,需要进行配置.否则后面supabase镜像无法启动.按照如下图所示进行配置

在这里插入图片描述
如有问题可以进一步参考官方指导.
https://supabase.com/docs/guides/local-development?queryGroups=package-manager&package-manager=npm

安装Supabase CLI

npm install supabase --save-dev

初始化项目

在您的存储库中,初始化 Supabase 项目:

npx supabase init

启动 Supabase 堆栈

npx supabase start

查看本地 Supabase 实例http://localhost:54323

查看状态 npx supabase status

PS D:\AndroidProject\BDCamera\doc\server\supabase_cli> npx supabase status
Stopped services: [supabase_imgproxy_supabase_cli supabase_pooler_supabase_cli]
supabase local development setup is running.

         API URL: http://127.0.0.1:54321
     GraphQL URL: http://127.0.0.1:54321/graphql/v1
  S3 Storage URL: http://127.0.0.1:54321/storage/v1/s3
          DB URL: postgresql://postgres:postgres@127.0.0.1:54322/postgres
      Studio URL: http://127.0.0.1:54323
    Inbucket URL: http://127.0.0.1:54324
      JWT secret: super-secret-jwt-token-with-at-least-32-characters-long
        anon key: eyJhbGciOiJIUzI1NiIsInR5c,,,,,,,,,,,,,,,,,,,,,,blYTn_I0
service_role key: eyJhbGciOiJIUzI1NiIsInR5cCI........................p7fsn3W0YpN81IU
   S3 Access Key: 625729a08b95.......a663f3a23c
   S3 Secret Key: 850181e4652dd023b7a9............d487ee0cc3254aed6eda37307425907
       S3 Region: local

本地环境准备完毕.
避坑指南 启动服务之前,需要打开docker 设置中的 Expose daemon on tcp://localhost:2375 without TLS, 否则
supabase_vector_supabase_cli镜像会频繁重启,导致失败.

在本地开发 Edge Functions

创建 Edge 函数

npx supabase functions new hello-function

这将在您的文件夹中创建一个函数存根:supabase
└── supabase
├── functions
│ └── hello-world
│ │ └── index.ts ## Your function code
└── config.toml

使用vscode等编辑器打开 index.ts文件查看,默认生成代码如下:

// Follow this setup guide to integrate the Deno language server with your editor:
// https://deno.land/manual/getting_started/setup_your_environment
// This enables autocomplete, go to definition, etc.

// Setup type definitions for built-in Supabase Runtime APIs
import "jsr:@supabase/functions-js/edge-runtime.d.ts"

console.log("Hello from Functions!")

Deno.serve(async (req) => {
  const { name } = await req.json()
  const data = {
    message: `Hello 你好! ${name}!`,
  }

  return new Response(
    JSON.stringify(data),
    { headers: { "Content-Type": "application/json" } },
  )
})

/* To invoke locally:

  1. Run `supabase start` (see: https://supabase.com/docs/reference/cli/supabase-start)
  2. Make an HTTP request:

  curl -i --location --request POST 'http://127.0.0.1:54321/functions/v1/hello-function' \
    --header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInxxxxcccccccccccccccccccccccccccccccccccccccccYTn_I0' \
    --header 'Content-Type: application/json' \
    --data '{"name":"Functions"}'

*/

在本地运行 Edge Functions

测试之前需要重启以下本地 supabase

npx supabase stop
npx supabase start

使用postman 或 curl访问, 最好用 Git bash 终端执行

curl -i --location --request POST 'http://127.0.0.1:54321/functions/v1/hello-function' \
    --header 'Authorization: Bearer eyJhbGciOiJIUzI1xxxxxxxx5cCI6IkpXVCJ9.eyJpc3MiOiJzd................YTn_I0' \
    --header 'Content-Type: application/json' \
    --data '{"name":"Functions"}'

输出如下,表示已经成功返回:

% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    68  100    48  100    20     37     15  0:00:01  0:00:01 --:--:--    53HTTP/1.1 200 OK
Server: nginx
Date: Mon, 05 May 2025 08:42:00 GMT
Content-Type: application/json
Content-Length: 48
Connection: keep-alive
vary: Accept-Encoding
Access-Control-Allow-Origin: *
X-Kong-Upstream-Latency: 1254
X-Kong-Proxy-Latency: 1
Via: kong/2.8.1
Strict-Transport-Security: max-age=31536000

{"message":"Hello 你好,太棒了! Functions!"}

可以使用vscode编辑 index.ts 保存后,是实时生效的.

将本地开发好的边函数 Edge Functions 部署到自托管的supabase

如果你不清楚如何私有化, 请查看私有部署supabase完整手册-1,详细介绍了如何私有化部署supabase.

手动部署

找到本地开发好的 函数目录
~\supabase\functions\hello-function
将整个目录复制到服务端supabase目录下
/www/supabase-project/volumes/functions

将函数放入后,默认情况下就可以直接访问了.并且不需要jwt验证.

访问测试:

$ curl -i --location --request POST 'https://ctaias.com/functions/v1/hello-function'  --header 'Content-Type: application/json'     --data '{"name":"Functions"}'
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    68  100    48  100    20    721    300 --:--:-- --:--:-- --:--:--  1062HTTP/1.1 200 OK
Server: nginx
Date: Mon, 05 May 2025 08:38:32 GMT
Content-Type: application/json
Content-Length: 48
Connection: keep-alive
vary: Accept-Encoding
Access-Control-Allow-Origin: *
X-Kong-Upstream-Latency: 35
X-Kong-Proxy-Latency: 2
Via: kong/2.8.1
Strict-Transport-Security: max-age=31536000

{"message":"Hello 你好,太棒了! Functions!"}

打开服务端jwt验证

安全起见,最好是打开边函数的jwt验证,但是目前它不支持 对不同的函数分别设置,也就是如果打开jwt,所有的函数调用都会要求提供jwt.

找到服务端supabase目录,编辑 .env 文件.

############
#Functions - Configuration for Functions
############
#NOTE: VERIFY_JWT applies to all functions. Per-function VERIFY_JWT is not supported yet.
FUNCTIONS_VERIFY_JWT=true

编辑后重启服务.

安卓客户端调用测试

目前我已经将hello-function 的边函数部署到了自托管的服务器上,并且已经通过curl进行了测试.这一步使用安卓客户端进行调用.

dependencies {
    implementation("io.github.jan-tennert.supabase:functions-kt:VERSION")
}

在您的 SupabaseClient 中安装插件

val client = createSupabaseClient(
    supabaseUrl = "https://id.supabase.co",
    supabaseKey = "apikey"
) {
    
    //...
    
    install(Functions) {
        // settings
    }
    
}

函数调用

override suspend fun removeUser(): AuthErrorCode? {
        return try {
            val ret = functions.invoke(function = "hello-function", body=mapOf("name" to "王鹏"))
            val data = ret.body<String>()
            Log.d("AuthenticationRepositoryImpl", "removeUser, data:  $data")
            null
        } catch (e: AuthRestException) {
            if(BuildConfig.DEBUG)
                Log.e("AuthenticationRepositoryImpl", "removeUser", e)
            e.errorCode
        }
    }

有关边函数开发的更多信息, 参考官方的开发手册:
https://supabase.com/docs/guides/functions

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值