搜尋套件、儲存庫與 APP 分類

套件詳情v1.1.2

surrealdb

純 Dart 編寫的 SurrealDB 客戶端。自動重連,類型化函數

AndroidiOSWebmacOSWindowsLinux
近 30 天下載
61
喜歡數
38
Pub 分數
150

安裝套件

flutter pub add surrealdb

套件介紹

根據套件公開資料產生的選型評估,僅供參考。

SurrealDB 的純 Dart 客戶端,提供自動重連和類型化函數。專為跨多個平台的無縫整合而設計,讓開發者能有效率地在 Flutter 應用中與 SurrealDB 資料庫互動。該套件抽象了底層網路細節,提供查詢、訂閱和驗證的乾淨 API。其類型安全的函數可減少執行時錯誤並提升開發速度。非常適合需要可靠資料庫連接的即時應用。

適用情境

  • 即時資料同步
  • 跨平台資料庫存取
  • 類型安全的查詢執行
  • 網路遺失後的自動重連
  • 無伺服器後端整合
  • 離線優先的應用程式開發

主要特色

  • 連接丟失時自動重連
  • 類型化函數支援
  • 純 Dart 實現
  • 多平台相容性
  • 輕便高效
  • 安全的身份驗證處理

適合對象

  • 使用 SurrealDB 的 Flutter 開發人員
  • 需要即時資料庫更新的應用
  • 需要跨平台資料庫客戶端的專案
  • 開發者優先考慮類型安全
  • 建構可擴展後端服務的團隊
  • 網路狀況不穩定的應用程式

使用建議

  • 需要一個正在運行的 SurrealDB 實例
  • 僅限SurrealDB特定功能
  • 可能需要為複雜查詢進行額外設定
  • 依賴外部SurrealDB伺服器的穩定性
  • 不適用於非 SurrealDB 資料庫
  • 需要身份驗證設定

原始 README

以下為關聯原始碼儲存庫的 README 原文快照,最新內容請造訪原始碼儲存庫。

SurrealDB Client For Dart & Flutter

Pub Version Tests GitHub Issues or Pull Requests

This is a Dart client library for interacting with SurrealDB, a highly scalable, distributed, and real-time database. This library enables developers to connect to SurrealDB instances, execute queries, authenticate users, and interact with database resources via WebSocket communication.

Features

  • ⚡ Connect and Disconnect: Establish or close a persistent WebSocket connection to a SurrealDB instance.
  • 🔐 Authentication: Authenticate with a token to manage access to the database.
  • 🗄️ Database Interaction: Use namespaces and databases, retrieve user information, and fetch database versions.
  • 🔄 Live Queries: Support for live querying via WebSocket streams.
  • ⚙️ Customizable Options: Set connection options and behavior using SurrealDBOptions.

Installation

Add the following to your pubspec.yaml:

dependencies:
  surrealdb: ^1.0.0

Then run dart pub get or flutter pub get.

Usage

Connecting to SurrealDB

To connect to a SurrealDB, create a SurrealDB client instance and call the connect() method. You can also provide a token for authentication.

import 'package:surrealdb/surrealdb.dart';

void main() async {
  // Create a SurrealDB client instance
  final db = SurrealDB('ws://localhost:8000/rpc', token: 'your-auth-token');

  // Connect to the database
  db.connect();

  // Wait for the connection to be established
  await db.wait();

  // Use a specific namespace and database
  await db.use('namespace', 'database');

  // Fetch version information
  final version = await db.version();
  print('SurrealDB version: $version');

  // Close the connection when done
  db.close();
}
Authentication

SurrealDB requires authentication to access resources. You can sign up, sign in, and authenticate users using the SurrealDB client.

Signing Up a User

To create a new user:

final token = await db.signup(
  user: 'new_user',
  pass: 'password123',
  namespace: 'namespace',
  database: 'database',
  access: 'users',
);
print('User signed up with token: $token');
Signing In

To sign in an existing user:

final token = await db.signin(
  user: 'existing_user', 
  pass: 'password123',
  namespace: 'namespace',
  database: 'database',
  access: 'users',
);
print('User signed in with token: $token');
Token Authentication

You can also authenticate with a token:

await db.authenticate('your-auth-token');
Middleware

SurrealDB Flutter client supports middleware that allows you to intercept and modify requests before they are sent to the database. This is particularly useful for implementing token refresh functionality or adding logging.

Adding Middleware

You can add middleware using the addMiddleware method:

db.addMiddleware((method, params, next) async {
  // Do something before the request
  print('Before request: $method with params: $params');
  
  // Execute the request
  final result = await next();
  
  // Do something after the request
  print('After request: $method with result: $result');
  
  return result;
});

Multiple middleware functions can be added, and they will be executed in the order they were added.

Token Refresh Example

Here's how you can implement token refresh using middleware:

db.addMiddleware((method, params, next) async {
  try {
    // Try to execute the request normally
    return await next();
  } catch (e) {
    // If we get an authentication error
    if (e.toString().contains('authentication invalid')) {
      // Refresh the token (implement your token refresh logic)
      final newToken = await refreshToken(); 
      
      // Re-authenticate with the new token
      await db.authenticate(newToken);
      
      // Retry the original request
      return await next();
    }
    // For other errors, just rethrow
    rethrow;
  }
});

This middleware will catch authentication errors, refresh the token, and retry the original request automatically.

Basic Queries

SurrealDB allows executing a variety of commands, including CRUD operations (Create, Read, Update, Delete) via queries. Here's how you can perform simple database operations.

3.1 Create Records
final data = {'title': 'My first post', 'content': 'Hello, SurrealDB!'};
final result = await db.create('posts', data);
print('Created record: $result');
3.2 Read Records

To retrieve records, you can use the select method.

final posts = await db.select('posts');
print('Fetched posts: $posts');

You can also use queries to filter or manipulate the data:

final specificPosts = await db.query(
  r'SELECT * FROM posts WHERE title = $title',
  {'title': 'My first post'},
);
print('Posts matching criteria: $specificPosts');
3.3 Update Records

Updating records is done by specifying the table and ID of the record:

final updatedData = {'title': 'Updated post title'};
await db.update('posts:id', updatedData);
print('Record updated successfully');
3.4 Delete Records

To delete a record:

await db.delete('posts:id');
print('Record deleted');
Live Queries

SurrealDB supports live queries over WebSocket. Use the LiveQuery class for subscribing to changes in data.

final liveQuery = await db.liveQuery('LIVE SELECT * FROM posts WHERE active = true');
liveQuery.stream.listen((event) {
  print('Received update: ${event.result}');
});

await db.create('posts', {
  'title': 'My first post',
});
await db.create('posts', {
  'title': 'My second post',
  'active': true
});

You can read more about all the available methods and classes in the API documentation.

Contributions

Contributions are welcome! Feel free to submit issues, feature requests, or pull requests to improve this library.

License

This project is licensed under the MIT License. See the LICENSE file for more details.

所屬分類

依賴

依賴清單 2 項

原始碼儲存庫

使用此套件的專案

暫無相關資料。