空のディレクトリから Supabase の関数まで
Dart で書く Supabase Edge Function を順を追って説明します。プロジェクトのテーブルに対する小さな REST API を、まずノート PC で実行し、それからデプロイします。以下の手順のうち、最後のデプロイ (ホスト型プロジェクトへのデプロイ) を除く各ステップは、Supabase CLI のローカルスタックに対して、書かれたとおりに実行しました。最後のステップは CLI のドキュメントに載っているコマンドを使っており、実行はしていません。
必要なもの: Dart SDK、Supabase CLI、そしてローカルスタック用の Docker。
1. プロジェクト
mkdir notes_function && cd notes_function
supabase init # makes supabase/config.toml
mkdir -p bin lib/src lib/resources test supabase/migrations
pubspec.yaml:
name: notes_function
publish_to: none
environment:
sdk: ^3.13.0
dependencies:
spring_boot_starter_edge: ^0.9.0 # the function, with the web starter
spring_boot_starter_security: ^0.9.0 # checks the project's tokens
spring_boot_starter_supabase: ^0.9.0 # the project's tables as repositories
dev_dependencies:
build_runner: ^2.17.0
spring_core_dart_generator: ^0.9.0
test: ^1.33.0
dart pub get
2. アプリケーション
bin/main.dart、エントリーポイントのすべてです。
import 'package:spring_boot_starter_edge/spring_boot_starter_edge.dart';
import 'spring_gen/main.spring.dart';
@SpringBootApplication()
void main() => runFetchApplication(() => springApplication);
lib/src/note.dart、テーブルとそのリポジトリです。
import 'package:spring_boot_starter_supabase/spring_boot_starter_supabase.dart';
/// A row of the table `notes`.
@Introspected()
@Table('notes')
class Note {
Note({required this.text, this.id});
@Id()
int? id;
@NotBlank()
String text;
}
/// The table through the project's REST API, as the caller: the policy of
/// the table decides which rows a user sees.
abstract interface class Notes implements ListCrudRepository<Note, int> {}
lib/src/notes_controller.dart、エンドポイントと、それを呼べる人です。
import 'package:notes_function/src/note.dart';
import 'package:spring_boot_starter_security/spring_boot_starter_security.dart';
@RestController()
class NotesController {
NotesController(this.notes);
final Notes notes;
/// Open to everyone.
@GetMapping('/health')
Map<String, Object?> health() => {'status': 'UP'};
/// The caller's notes.
@GetMapping('/notes')
Future<List<Note>> list() => notes.findAll();
@PostMapping('/notes')
@ResponseStatus(HttpStatus.created)
Future<Note> add(@RequestBody() @Valid() Note note) => notes.save(note);
/// Who calls, as read from the checked token.
@GetMapping('/me')
Map<String, Object?> me(Authentication caller) => {'id': caller.name};
}
@Configuration()
class SecurityConfig {
@Bean()
SecurityFilterChain api(HttpSecurity http) => http
.authorizeHttpRequests(
(auth) => auth
.requestMatchers('/health')
.permitAll()
.anyRequest()
.authenticated(),
)
.sessionManagement(
(session) =>
session.sessionCreationPolicy(SessionCreationPolicy.stateless),
)
.csrf((csrf) => csrf.disable())
.oauth2ResourceServer((server) => server.jwt())
.build();
}
ベアラートークンは、プロジェクトのユーザーのアクセストークンです。Supabase スターターが、リソースサーバーにプロジェクトのキー、issuer、audience を渡します。関数には、どのノートが誰のものかというルールを書きません。呼び出し元のトークンをそのまま渡し、テーブルのポリシーが判断します。
lib/resources/application.yml:
spring:
application:
name: notes
main:
banner-mode: off
# In the function these come from the platform; here for `dart run`.
supabase:
url: ${SUPABASE_URL:http://127.0.0.1:54321}
anon-key: ${SUPABASE_ANON_KEY:}
supabase/migrations/20260101000000_notes.sql、ポリシー付きのテーブルです。
create table public.notes (
id bigint generated by default as identity primary key,
text text not null,
owner uuid not null default auth.uid()
);
alter table public.notes enable row level security;
create policy own_notes on public.notes
for all to authenticated
using (owner = (select auth.uid()))
with check (owner = (select auth.uid()));
grant select, insert, update, delete on public.notes to authenticated;
アプリケーションのコードを生成します (Bean を変更するたびに再実行してください)。
dart run build_runner build
3. サーバーとして実行する
Dart VM 上の同じ main は通常のサーバーです。書いてデバッグする最も速い方法です。
SERVER_PORT=8089 dart run bin/main.dart
curl localhost:8089/health # {"status":"UP"}
curl -i localhost:8089/notes # 401: no token
4. テスト
test/function_test.dart は、プラットフォームがするのと同じようにアプリケーションを、プラットフォームなしで呼び出します。
import 'package:spring_boot_starter_edge/spring_boot_starter_edge.dart';
import 'package:test/test.dart';
import '../bin/spring_gen/main.spring.dart';
void main() {
final function = FetchApplication(() => springApplication);
tearDownAll(function.close);
Future<int> status(String path) async => (await function.fetch(
FetchRequest('GET', Uri.parse('https://example.com$path')),
)).status;
test('health is open, the notes are not', () async {
expect(await status('/health'), 200);
expect(await status('/notes'), 401);
});
}
dart test
5. 関数としてローカルで実行する
アプリケーション自身がトークンを検証することを、supabase/config.toml でプラットフォームに伝えます。これがないと、ゲートウェイはトークンのないすべてのリクエストに 401 (Missing authorization header) を返します。/health も例外ではありません。
[functions.notes]
verify_jwt = false
# The local stack only: its functions reach the project at
# http://kong:8000, while its tokens name the address the clients use.
[edge_runtime.secrets]
SPRING_SUPABASE_AUTH_ISSUER = "http://127.0.0.1:54321/auth/v1"
関数を supabase/functions/notes/ にビルドしてから、スタックを起動します (スタックは起動時に関数を見つけられる必要があります。初回以降は、古いビルドを提供していたインスタンスがアイドルになれば (約 30 秒後)、再起動なしで新しいビルドが使われます)。
dart run spring_boot_starter_edge:build --platform supabase --name notes
supabase start
supabase start はアドレスとキーを表示します。supabase status で再表示できます。anon キーを ANON_KEY に入れて実行します。
URL=http://127.0.0.1:54321
curl $URL/functions/v1/notes/health
# A user of the project, and their access token.
TOKEN=$(curl -s "$URL/auth/v1/signup" -H "apikey: $ANON_KEY" \
-H 'Content-Type: application/json' \
-d '{"email": "[email protected]", "password": "correct horse"}' | jq -r .access_token)
curl $URL/functions/v1/notes/me -H "Authorization: Bearer $TOKEN"
curl $URL/functions/v1/notes/notes -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"text": "first"}' # 201
curl $URL/functions/v1/notes/notes -H "Authorization: Bearer $TOKEN"
関数の名前 (notes) はそのアドレスの最初のセグメントであり、マッピングの一部ではありません。@GetMapping('/health') は /functions/v1/notes/health に応答します。別のユーザーがノートを要求すると空のリストが返ります。ノートを隠しているのは関数ではなく、テーブルのポリシーです。
関数のログ (起動、スターターの警告、エラー) は、スタックの Edge Runtime のログです。docker logs -f supabase_edge_runtime_<project id> で確認します。
supabase/functions/notes/ を .gitignore に追加してください。これは書くものではなく、ビルドされるものです。
6. デプロイする
supabase login
supabase link --project-ref <ref> # <ref>.supabase.co
supabase db push # the migration of step 2
dart run spring_boot_starter_edge:build --platform supabase --name notes
supabase functions deploy notes
curl https://<ref>.supabase.co/functions/v1/notes/health
ホスト型プロジェクトでは [edge_runtime.secrets] は不要です。そこでは関数とトークンが同じアドレスを指します。プロジェクト自身の変数以外にアプリケーションが環境から読むものは、プロジェクトのシークレットです。supabase secrets set NAME=value で設定します。
プッシュのたびにデプロイするには、次を実行します。
dart run spring_boot_starter_edge:workflow --platform supabase --name notes
これは .github/workflows/deploy-notes.yml を書きます。リポジトリにシークレット SUPABASE_ACCESS_TOKEN と SUPABASE_PROJECT_REF を設定してください。
次に読むもの
- 関数のデプロイ: Cloudflare と AWS での同じ手順、WebAssembly (
--target wasm)、シークレット、スケジュール。 - 関数が異なる点: リクエスト間のタイマーがない (
@Scheduled)、インスタンス間でメモリに保持されるものがない (キャッシュ、セッション、メモリ内のレートリミッター)。代わりに使うもの。 - すべてのインスタンスで共有されるレート制限: プロジェクトのデータベース関数を使う
@RateLimiter。example/supabase/functionがその例です。