开发小技巧
Tips for getting started with Edge Functions.
这里有一些建议,适合你刚开始开发 Edge Functions 时参考。
🌐 Here are a few recommendations when you first start developing Edge Functions.
使用 HTTP 方法 #
🌐 Using HTTP methods
Edge Functions 支持 GET、POST、PUT、PATCH、DELETE 和 OPTIONS。一个函数可以根据请求的 HTTP 方法执行不同的操作。查看 构建 RESTful 服务的示例 了解如何在你的函数中处理不同的 HTTP 方法。
🌐 Edge Functions support GET, POST, PUT, PATCH, DELETE, and OPTIONS. A Function can be designed to perform different actions based on a request's HTTP method. See the example on building a RESTful service to learn how to handle different HTTP methods in your Function.
不支持 HTML
不支持 HTML 内容。返回 text/html 的 GET 请求将被重写为 text/plain。
🌐 HTML content is not supported. GET requests that return text/html will be rewritten to text/plain.
命名边缘函数 #
🌐 Naming Edge Functions
我们建议用连字符来命名函数,因为连字符在所有命名规范(下划线命名、驼峰命名、帕斯卡命名)中最适合用于 URL。
🌐 We recommend using hyphens to name functions because hyphens are the most URL-friendly of all the naming conventions (snake_case, camelCase, PascalCase).
整理你的 Edge 函数 #
🌐 Organizing your Edge Functions
我们建议开发“肥函数”。这意味着你应该开发少量的大函数,而不是很多小函数。开发函数时一个常见的模式是你需要在两个或更多函数之间共享代码。为此,你可以将任何共享代码存放在以下划线开头的文件夹中(_)。我们还建议为单元测试单独建一个文件夹,文件夹名包括函数名称,后面加上-test后缀。
我们推荐这样的文件夹结构:
🌐 We recommend developing "fat functions". This means that you should develop few large functions, rather than many small functions. One common pattern when developing Functions is that you need to share code between two or more Functions. To do this, you can store any shared code in a folder prefixed with an underscore (_). We also recommend a separate folder for Unit Tests including the name of the function followed by a -test suffix.
We recommend this folder structure:
1└── supabase2 ├── functions3 │ ├── import_map.json # A top-level import map to use across functions.4 │ ├── _shared5 │ │ ├── supabaseAdmin.ts # Supabase client with SECRET key.6 │ │ └── supabaseClient.ts # Supabase client with PUBLISHABLE key.7 │ │ └── cors.ts # Reusable CORS headers.8 │ ├── function-one # Use hyphens to name functions.9 │ │ └── index.ts10 │ └── function-two11 │ │ └── index.ts12 │ └── tests13 │ └── function-one-test.ts14 │ └── function-two-test.ts15 ├── migrations16 └── config.toml使用 config.toml #
🌐 Using config.toml
像 JWT 验证 和 导入映射位置 这样的单个功能配置可以通过 config.toml 文件来设置。
🌐 Individual function configuration like JWT verification and import map location can be set via the config.toml file.
1[functions.hello-world]2verify_jwt = false3import_map = './import_map.json'不使用 TypeScript #
🌐 Not using TypeScript
当你创建一个新的 Edge 函数时,它默认会使用 TypeScript。不过,你也可以使用纯 JavaScript 来编写和部署 Edge 函数。
🌐 When you create a new Edge Function, it will use TypeScript by default. However, it is possible to write and deploy Edge Functions using pure JavaScript.
将你的函数保存为一个 JavaScript 文件(例如 index.js),然后按如下方式更新 supabase/config.toml:
🌐 Save your Function as a JavaScript file (e.g. index.js) and then update the supabase/config.toml as follows:
entrypoint 仅在 Supabase CLI 版本 1.215.0 或更高版本中可用。
1[functions.hello-world]2# other entries3entrypoint = './functions/hello-world/index.js' # path must be relative to config.toml你可以将任何 .ts、.js、.tsx、.jsx 或 .mjs 文件用作函数的 entrypoint。
🌐 You can use any .ts, .js, .tsx, .jsx or .mjs file as the entrypoint for a Function.
错误处理 #
🌐 Error handling
supabase-js 库提供了几种错误类型,你可以用它们来处理调用 Edge Functions 时可能发生的错误:
🌐 The supabase-js library provides several error types that you can use to handle errors that might occur when invoking Edge Functions:
1import { FunctionsFetchError, FunctionsHttpError, FunctionsRelayError } from '@supabase/supabase-js'23const { data, error } = await supabase.functions.invoke('hello', {4 headers: { 'my-custom-header': 'my-custom-header-value' },5 body: { foo: 'bar' },6})78if (error instanceof FunctionsHttpError) {9 const errorMessage = await error.context.json()10 console.log('Function returned an error', errorMessage)11} else if (error instanceof FunctionsRelayError) {12 console.log('Relay error:', error.message)13} else if (error instanceof FunctionsFetchError) {14 console.log('Fetch error:', error.message)15}数据库函数 vs 边缘函数 #
🌐 Database Functions vs Edge Functions
对于数据量大的操作,我们建议使用 数据库函数,这些函数在你的数据库内执行,并可以通过 REST 和 GraphQL API 远程调用。
🌐 For data-intensive operations we recommend using Database Functions, which are executed within your database and can be called remotely using the REST and GraphQL API.
对于需要低延迟的使用场景,我们推荐 Edge Functions,它们是全球分布的,并且可以使用 TypeScript 编写。
🌐 For use-cases which require low-latency we recommend Edge Functions, which are globally-distributed and can be written in TypeScript.