iT邦幫忙

2026 iThome 鐵人賽

DAY 16
0
Build on Google AI

將考國際證照的應用程式變成開源系列 第 26

api-integration : PowerSync Setup

  • 分享至 

  • xImage
  •  

PowerSync 設定指南

1. 帳號與專案設定

  • PowerSync Cloud 建立帳號。
  • 設定一個新實例,並將其連接到您的 Supabase PostgreSQL 資料庫。
  • 在應用程式設定中配置多個端點 (4 個主要端點 + 備用配對) 以實現高可用性。

2. 同步規則

powersync_rules.yaml 檔案部署至您的 PowerSync 實例。

bucket_definitions:
  user_data:
    parameters:
      - select: current_user_id()
    data:
      - select: * from profiles where id = bucket.current_user_id()
  questions:
    data:
      - select: * from questions where is_approved = true
  • 基於角色的 Bucket 設定:使用 JWT 權杖參數來限制使用者可以同步哪些資料桶 (Buckets),確保 Viewer 只能取得已發布的認證考試題目,包含子網路與連接埠的練習題。

3. SDK 安裝

pubspec.yaml 依賴項目

dependencies:
  powersync_flutter: latest
  powersync_sqlcipher: latest
  flutter_secure_storage: latest

4. 程式碼整合

綱要 (Schema) 定義

定義您的本地端綱要以符合 Supabase 資料表:

import 'package:powersync_flutter/powersync_flutter.dart';

const schema = Schema([
  Table('questions', [
    Column.text('title'),
    Column.text('type'),
    Column.text('options'),
    Column.text('correct_answer'),
  ]),
]);

Connector 實作

實作 PowerSync 連接器來處理 fetchCredentialsuploadData

class BackendConnector extends PowerSyncBackendConnector {
  @override
  Future<PowerSyncCredentials?> fetchCredentials() async {
    // 從您的驗證提供者取得 JWT
  }

  @override
  Future<void> uploadData(PowerSyncDatabase database) async {
    // 處理離線資料異動
  }
}

5. 加密

  • 使用 SQLCipher 來加密本機的 SQLite 資料庫。
  • 使用 FlutterSecureStorage 在裝置上安全地產生並儲存加密金鑰。

6. 必要的環境變數

變數 說明
POWERSYNC_URL PowerSync 實例的 URL
POWERSYNC_ENDPOINTS 以逗號分隔的備用端點清單

7. 常見問題排除

  • 資料庫鎖定錯誤:確保使用正確的並發讀寫設定,並且在應用程式生命週期的早期初始化 PowerSync。
  • 特定資料列同步失敗:檢查您的 powersync_rules.yaml 語法,並確保 JWT 權杖包含正確的使用者宣告 (Claims)。

上一篇
api-integration : firebase-setup , supabase-setup , mongodb-setup
下一篇
api-integration : revenuecat-setup
系列文
將考國際證照的應用程式變成開源27
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言