SurrealDB용 순수 Dart 클라이언트로 자동 재연결 및 타입 안정성 함수를 제공합니다. 다양한 플랫폼 간의 원활한 통합을 위해 설계되어 Flutter 앱에서 SurrealDB 데이터베이스와 효율적으로 상호작용할 수 있도록 합니다. 패키지는 저수준 네트워킹 세부 정보를 추상화하여 쿼리, 구독 및 인증을 위한 깔끔한 API를 제공합니다. 타입 안정성 함수는 런타임 오류를 줄이고 개발 속도를 향상시킵니다. 신뢰할 수 있는 데이터베이스 연결이 필요한 실시간 앱에 이상적입니다.
사용 사례
실시간 데이터 동기화
다중 플랫폼 데이터베이스 접근
형 안전한 쿼리 실행
네트워크 손실 후 자동 재연결
서버리스 백엔드 통합
오프라인 우선 앱 개발
주요 기능
연결 손실 시 자동 재연결
타입화된 함수 지원
순수한 다트 구현
다중 플랫폼 호환성
가볍고 효율적
보안 인증 처리
적합한 대상
SurrealDB를 사용하는 Flutter 개발자
실시간 데이터베이스 업데이트가 필요한 앱
플랫폼에 관계없이 데이터베이스 클라이언트가 필요한 프로젝트
유형 안전성을 우선시하는 개발자
확장 가능한 백엔드 서비스를 구축하는 팀
신뢰할 수 없는 네트워크 조건을 가진 애플리케이션
고려 사항
실행 중인 SurrealDB 인스턴스가 필요합니다
SurrealDB 전용 기능에 한정
복잡한 쿼리에 대해 추가 설정이 필요할 수 있습니다
외부 SurrealDB 서버의 안정성에 의존
비-SurrealDB 데이터베이스에는 적합하지 않습니다
인증 구성이 필요합니다
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
SurrealDB Client For Dart & Flutter
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';
voidmain() async {
// Create a SurrealDB client instancefinal db = SurrealDB('ws://localhost:8000/rpc', token: 'your-auth-token');
// Connect to the database
db.connect();
// Wait for the connection to be establishedawait db.wait();
// Use a specific namespace and databaseawait db.use('namespace', 'database');
// Fetch version informationfinal 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 requestprint('Before request: $method with params: $params');
// Execute the requestfinal result = awaitnext();
// Do something after the requestprint('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 normallyreturnawaitnext();
} catch (e) {
// If we get an authentication errorif (e.toString().contains('authentication invalid')) {
// Refresh the token (implement your token refresh logic)final newToken = awaitrefreshToken();
// Re-authenticate with the new tokenawait db.authenticate(newToken);
// Retry the original requestreturnawaitnext();
}
// For other errors, just rethrowrethrow;
}
});
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');