### Complete Working Example with User Data Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Quick‐Start A comprehensive example demonstrating the setup and usage of the SignalDB Tauri Adapter with a 'User' data type. It includes inserting, querying, updating, and deleting user records, showcasing a full application flow. ```typescript import { Collection } from '@signaldb/core'; import { createTauriFileSystemAdapter } from '@pitzzahh/signaldb-adapter-tauri'; // Define your data structure interface User { id: string; name: string; email: string; role: 'admin' | 'user'; createdAt: Date; } // Create the persistence adapter const userAdapter = createTauriFileSystemAdapter('users.json'); // Create a reactive collection with persistence const users = new Collection({ persistence: userAdapter }); // Example usage async function demonstrateUsage() { // Insert users const admin = users.insert({ id: '1', name: 'John Doe', email: 'john@example.com', role: 'admin', createdAt: new Date() }); const regularUser = users.insert({ id: '2', name: 'Jane Smith', email: 'jane@example.com', role: 'user', createdAt: new Date() }); // Query users const allUsers = users.find({}).fetch(); console.log('All users:', allUsers); const admins = users.find({ role: 'admin' }).fetch(); console.log('Admin users:', admins); // Update a user users.updateOne( { id: '2' }, { $set: { role: 'admin' } } ); // Remove a user users.removeOne({ id: '1' }); console.log('Final user count:', users.find({}).count()); } // Run the demo demonstrateUsage().catch(console.error); ``` -------------------------------- ### Install Peer Dependencies Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Installation Installs the core SignalDB and necessary Tauri dependencies. ```bash # Core SignalDB npm install @signaldb/core # Tauri dependencies npm install @tauri-apps/api @tauri-apps/plugin-fs ``` -------------------------------- ### Create New Tauri Project with SignalDB Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Installation Commands to create a new Tauri project and install SignalDB and its adapter. ```bash # Create new Tauri project npm create tauri-app@latest my-app cd my-app # Install SignalDB and the adapter npm install @signaldb/core @pitzzahh/signaldb-adapter-tauri # Install Tauri dependencies npm install @tauri-apps/api @tauri-apps/plugin-fs ``` -------------------------------- ### Install SignalDB Tauri Adapter Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Installation Installs the SignalDB Tauri Adapter using different package managers. ```bash # Using npm npm install @pitzzahh/signaldb-adapter-tauri # Using yarn yarn add @pitzzahh/signaldb-adapter-tauri # Using pnpm pnpm add @pitzzahh/signaldb-adapter-tauri # Using bun bun add @pitzzahh/signaldb-adapter-tauri ``` -------------------------------- ### SignalDB Collection Usage Examples Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Quick‐Start Demonstrates common operations on a SignalDB collection, including inserting new data, finding existing data, updating records, and deleting records. All operations are automatically persisted. ```typescript // Add a todo - automatically persisted to disk const newTodo = todos.insert({ id: crypto.randomUUID(), title: 'Learn SignalDB Tauri Adapter', completed: false, createdAt: new Date() }); // Find todos - loads from disk if needed const allTodos = todos.find({}).fetch(); console.log('All todos:', allTodos); // Update a todo - changes persisted automatically todos.updateOne( { id: newTodo.id }, { $set: { completed: true } } ); // Delete a todo - removal persisted automatically todos.removeOne({ id: newTodo.id }); ``` -------------------------------- ### Troubleshoot Peer Dependencies Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Installation Installs all peer dependencies explicitly to resolve warnings. ```bash # Install all peer dependencies explicitly npm install @signaldb/core@^1.0.0 @tauri-apps/api@^2.0.0 @tauri-apps/plugin-fs@^2.4.0 ``` -------------------------------- ### Configure Tauri Filesystem Plugin Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Installation Configures the Tauri filesystem plugin in tauri.conf.json and Cargo.toml, and initializes it in main.rs. ```json { "plugins": { "fs": { "all": true, "scope": ["$APPLOCALDATA/*"] } } } ``` -------------------------------- ### Initialize Tauri Filesystem Plugin Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Installation Initializes the Tauri filesystem plugin in the main Rust application file. ```rust fn main() { tauri::Builder::default() .plugin(tauri_plugin_fs::init()) .run(tauri::generate_context!()) .expect("error while running tauri application"); } ``` -------------------------------- ### Dynamic Collection Setup from Configuration Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Usage‐Examples Demonstrates a pattern for dynamically creating SignalDB collections based on a configuration object. This approach allows for flexible setup where collection names, filenames, and base directories can be defined in a configuration file. ```typescript import { Collection } from '@signaldb/core'; import { createTauriFileSystemAdapter } from '@pitzzahh/signaldb-adapter-tauri'; import { BaseDirectory } from '@tauri-apps/plugin-fs'; interface AppConfig { collections: { name: string; filename: string; baseDir?: BaseDirectory; }[]; } const config: AppConfig = { collections: [ { name: 'users', filename: 'users.json', baseDir: BaseDirectory.AppData }, { name: 'settings', filename: 'settings.json', baseDir: BaseDirectory.AppConfig }, { name: 'cache', filename: 'cache.json', baseDir: BaseDirectory.AppCache } ] }; // Create collections dynamically const collections = config.collections.reduce((acc, { name, filename, baseDir }) => { acc[name] = new Collection({ name, persistence: createTauriFileSystemAdapter(filename, { base_dir: baseDir || BaseDirectory.AppLocalData }) }); return acc; }, {} as Record); // Use collections await collections.users.insert({ id: '1', name: 'John', email: 'john@example.com' }); ``` -------------------------------- ### Performance Optimization Tips Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Quick‐Start Provides key recommendations for optimizing the performance of the SignalDB Adapter. These include using specific queries, implementing pagination for large datasets, considering the overhead of encryption for sensitive data, and utilizing indexes for frequently queried fields. ```English Performance Tips: 1. Use specific queries instead of loading all data 2. Implement pagination for large datasets 3. Consider encryption overhead for sensitive data 4. Use indexes for frequently queried fields ``` -------------------------------- ### Create SignalDB Collection with Persistence Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Quick‐Start Initializes a new SignalDB Collection, specifying the data type and the persistence adapter. This enables automatic data persistence to the file system. ```typescript const todos = new Collection({ persistence: adapter }); ``` -------------------------------- ### Configure Tauri Filesystem Plugin (Cargo.toml) Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Installation Adds the Tauri filesystem plugin dependency to Cargo.toml. ```toml [dependencies] tauri-plugin-fs = "2.0" ``` -------------------------------- ### Import SignalDB Tauri Adapter Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Quick‐Start Imports the necessary Collection class from the core SignalDB library and the createTauriFileSystemAdapter function from the Tauri adapter package. ```typescript import { Collection } from '@signaldb/core'; import { createTauriFileSystemAdapter } from '@pitzzahh/signaldb-adapter-tauri'; ``` -------------------------------- ### Migrate from IndexedDB to Tauri File System Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Migration‐Guide Provides code examples for migrating data from an IndexedDB persistence adapter to the Tauri File System adapter for SignalDB. It shows the setup for both adapters and a script to perform the data transfer. ```typescript import { Collection } from '@signaldb/core'; import createIndexedDBAdapter from '@signaldb/indexeddb'; const users = new Collection({ name: 'users', persistence: createIndexedDBAdapter('myapp', 'users') }); ``` ```typescript import { Collection } from '@signaldb/core'; import { createTauriFileSystemAdapter } from '@pitzzahh/signaldb-adapter-tauri'; const users = new Collection({ name: 'users', persistence: createTauriFileSystemAdapter('users.json') }); ``` ```typescript import { Collection } from '@signaldb/core'; import { createTauriFileSystemAdapter } from '@pitzzahh/signaldb-adapter-tauri'; import createIndexedDBAdapter from '@signaldb/indexeddb'; async function migrateFromIndexedDB() { // Create temporary collection with old adapter const oldCollection = new Collection({ name: 'users', persistence: createIndexedDBAdapter('myapp', 'users') }); // Get all data const allData = oldCollection.find({}); // Create new collection with Tauri adapter const newCollection = new Collection({ name: 'users', persistence: createTauriFileSystemAdapter('users.json') }); // Insert all data to new collection if (allData.length > 0) { await newCollection.insertMany(allData); console.log(`Migrated ${allData.length} records from IndexedDB`); } } // Run migration await migrateFromIndexedDB(); ``` -------------------------------- ### Define Data Type Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Quick‐Start Defines a TypeScript interface for the data structure that will be stored in the collection. This example shows a 'Todo' item with properties like id, title, completed status, and creation date. ```typescript interface Todo { id: string; title: string; completed: boolean; createdAt: Date; } ``` -------------------------------- ### Troubleshooting Common Issues Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Quick‐Start Offers solutions for common problems encountered with the SignalDB Adapter. This includes guidance on data not persisting (checking Tauri permissions, adapter configuration, console errors), performance issues (using indexes, pagination, checking encryption overhead), and type errors (TypeScript configuration, data type matching, peer dependencies). ```English Troubleshooting: Data Not Persisting? - Check Tauri filesystem permissions - Verify the adapter is properly configured - Look for console errors Performance Issues? - Consider using indexes for large datasets - Implement pagination for big collections - Check if encryption is causing overhead Type Errors? - Ensure proper TypeScript configuration - Check that data types match interface definitions - Verify peer dependencies are installed ``` -------------------------------- ### React Todo App with SignalDB Tauri Persistence Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Quick‐Start A React component demonstrating a Todo application with data persistence using the SignalDB Tauri adapter. It covers adding, completing, and deleting todos, with UI updates synchronized in real-time. ```react import React, { useState, useEffect } from 'react'; import { Collection } from '@signaldb/core'; import { createTauriFileSystemAdapter } from '@pitzzahh/signaldb-adapter-tauri'; interface Todo { id: string; title: string; completed: boolean; createdAt: Date; } // Create persistent collection const adapter = createTauriFileSystemAdapter('todos.json'); const todoCollection = new Collection({ persistence: adapter }); export default function TodoApp() { const [todos, setTodos] = useState([]); const [newTodoTitle, setNewTodoTitle] = useState(''); useEffect(() => { // Initial load setTodos(todoCollection.find({}).fetch()); // Watch for changes const observer = todoCollection.find({}).observe((newTodos) => { setTodos([...newTodos]); }); return () => observer.stop(); }, []); const addTodo = (e: React.FormEvent) => { e.preventDefault(); if (newTodoTitle.trim()) { todoCollection.insert({ id: crypto.randomUUID(), title: newTodoTitle.trim(), completed: false, createdAt: new Date() }); setNewTodoTitle(''); } }; const toggleTodo = (id: string) => { const todo = todoCollection.findOne({ id }); if (todo) { todoCollection.updateOne( { id }, { $set: { completed: !todo.completed } } ); } }; const removeTodo = (id: string) => { todoCollection.removeOne({ id }); }; return (

Todo App with Persistence

setNewTodoTitle(e.target.value)} placeholder="Enter a new todo" required />
    {todos.map(todo => (
  • toggleTodo(todo.id)} /> {todo.title}
  • ))}
); } ``` -------------------------------- ### Migrate from Memory Adapter to Tauri File System Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Migration‐Guide Illustrates the transition from using no persistence (memory adapter) to the Tauri File System adapter for SignalDB. Shows the setup for the new persistent adapter and lists the benefits of this migration. ```typescript import { Collection } from '@signaldb/core'; const users = new Collection({ name: 'users' // No persistence - data lost on restart }); ``` ```typescript import { Collection } from '@signaldb/core'; import { createTauriFileSystemAdapter } from '@pitzzahh/signaldb-adapter-tauri'; const users = new Collection({ name: 'users', persistence: createTauriFileSystemAdapter('users.json') }); ``` -------------------------------- ### Storage Best Practices: File Naming Conventions Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Storage‐Configuration Provides examples of good and bad file naming conventions for organizing application data. It recommends descriptive, hierarchical names for better clarity and maintainability, while cautioning against generic names. ```typescript // ✅ Good: Descriptive, hierarchical names const userProfiles = createTauriFileSystemAdapter('users/profiles.json'); const appSettings = createTauriFileSystemAdapter('config/app-settings.json'); const uiCache = createTauriFileSystemAdapter('cache/ui-state.json'); // ❌ Bad: Generic names const data1 = createTauriFileSystemAdapter('data.json'); const file2 = createTauriFileSystemAdapter('file.json'); ``` -------------------------------- ### Create Basic Tauri File System Adapter Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Quick‐Start Creates an instance of the Tauri file system adapter for persisting data. It takes a filename and optionally a generic type for the data structure. Data is stored in the application's local data directory by default. ```typescript // Basic adapter - data stored in app's local data directory const adapter = createTauriFileSystemAdapter('todos.json'); ``` -------------------------------- ### SignalDB Tauri Adapter Quick Example Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Home Demonstrates how to create a SignalDB collection with the Tauri file system adapter for automatic data persistence. This example shows defining a data type, creating the adapter, and initializing a collection. ```typescript import { Collection } from '@signaldb/core'; import { createTauriFileSystemAdapter } from '@pitzzahh/signaldb-adapter-tauri'; // Define your data type interface User { id: string; name: string; email: string; } // Create the adapter const adapter = createTauriFileSystemAdapter('users.json'); // Create a collection with persistence const users = new Collection({ persistence: adapter }); // Your data is now automatically persisted! users.insert({ id: '1', name: 'John Doe', email: 'john@example.com' }); ``` -------------------------------- ### Install @pitzzahh/signaldb-adapter-tauri Source: https://github.com/pitzzahh/signaldb-adapter-tauri/blob/main/README.md Instructions for installing the @pitzzahh/signaldb-adapter-tauri package using various package managers like npm, yarn, pnpm, and bun. ```bash # npm npm install @pitzzahh/signaldb-adapter-tauri # yarn yarn add @pitzzahh/signaldb-adapter-tauri # pnpm pnpm add @pitzzahh/signaldb-adapter-tauri # bun bun add @pitzzahh/signaldb-adapter-tauri ``` -------------------------------- ### Import and Use Adapter Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Installation Imports the createTauriFileSystemAdapter function from the SignalDB Tauri adapter in TypeScript. ```typescript import { createTauriFileSystemAdapter } from '@pitzzahh/signaldb-adapter-tauri'; ``` -------------------------------- ### Migrate from Local Storage to Tauri File System Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Migration‐Guide Demonstrates how to migrate data from a browser's Local Storage adapter to the Tauri File System adapter for SignalDB. Includes setup for both old and new adapters and a migration script to transfer data. ```typescript import { Collection } from '@signaldb/core'; import createLocalStorageAdapter from '@signaldb/localstorage'; const users = new Collection({ name: 'users', persistence: createLocalStorageAdapter('users') }); ``` ```typescript import { Collection } from '@signaldb/core'; import { createTauriFileSystemAdapter } from '@pitzzahh/signaldb-adapter-tauri'; const users = new Collection({ name: 'users', persistence: createTauriFileSystemAdapter('users.json') }); ``` ```typescript import { Collection } from '@signaldb/core'; import { createTauriFileSystemAdapter } from '@pitzzahh/signaldb-adapter-tauri'; import createLocalStorageAdapter from '@signaldb/localstorage'; async function migrateFromLocalStorage() { // Create temporary collection with old adapter const oldCollection = new Collection({ name: 'users', persistence: createLocalStorageAdapter('users') }); // Get all data from localStorage collection const allData = oldCollection.find({}); // Create new collection with Tauri adapter const newCollection = new Collection({ name: 'users', persistence: createTauriFileSystemAdapter('users.json') }); // Insert all data to new collection if (allData.length > 0) { await newCollection.insertMany(allData); console.log(`Migrated ${allData.length} records from localStorage`); } // Optional: Clear localStorage data localStorage.removeItem('users'); } // Run migration await migrateFromLocalStorage(); ``` -------------------------------- ### Add and Run Migrations Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Migration‐Guide Demonstrates how to instantiate a MigrationManager, add new migration tasks with versioning and descriptions, and then execute all pending migrations. ```typescript const migrationManager = new MigrationManager(); // Add migrations migrationManager.addMigration({ version: '1.1.0', description: 'Add encryption to user data', migrate: async () => { const migrator = new EncryptionMigrator(); await migrator.addEncryptionToExistingData('users.json', 'secret-key'); } }); migrationManager.addMigration({ version: '1.2.0', description: 'Update user schema', migrate: async () => { const migrator = new SchemaMigrator(); await migrator.migrateUserSchema('users.json'); } }); migrationManager.addMigration({ version: '1.3.0', description: 'Move files to new location', migrate: async () => { const migrator = new LocationMigrator(); await migrator.moveToNewLocation( 'users.json', BaseDirectory.AppCache, BaseDirectory.AppLocalData ); } }); // Run all pending migrations await migrationManager.runMigrations(); ``` -------------------------------- ### Configure Tauri Adapter Storage Location Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Quick‐Start Shows how to configure the Tauri file system adapter to store data in a different directory, such as the user's Documents folder, using the `base_dir` option and Tauri's `BaseDirectory` enum. ```typescript import { BaseDirectory } from '@tauri-apps/plugin-fs'; const adapter = createTauriFileSystemAdapter('todos.json', { // Store in documents directory instead of app local data base_dir: BaseDirectory.Document, // Security options security: { validateDecryptedData: true, allowPlaintextFallback: false } }); ``` -------------------------------- ### Implement Custom Encryption for SignalDB Adapter Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Quick‐Start Demonstrates how to add custom encryption and decryption functions to the Tauri file system adapter for enhanced data security. It includes placeholder functions for encryption/decryption and configuration options to enforce encryption. ```typescript // Simple encryption functions (use a proper library in production!) const encrypt = async (data: any): Promise => { const jsonString = JSON.stringify(data); // Use your preferred encryption library here return btoa(jsonString); // Base64 encoding (NOT secure!) }; const decrypt = async (encrypted: string): Promise => { // Use your preferred decryption library here const jsonString = atob(encrypted); // Base64 decoding return JSON.parse(jsonString); }; const secureAdapter = createTauriFileSystemAdapter('secure-todos.json', { encrypt, decrypt, security: { enforceEncryption: true, validateDecryptedData: true } }); ``` -------------------------------- ### File Storage Details Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Quick‐Start Describes the file storage mechanism used by the SignalDB Adapter in Tauri. Data is stored locally in the application's secure directory using human-readable JSON files for easy debugging. This approach ensures cross-platform compatibility on Windows, macOS, and Linux. ```English File Storage: - Local filesystem: data stored in app's secure directory - Human-readable format: JSON files for easy debugging - Cross-platform: works on Windows, macOS, and Linux ``` -------------------------------- ### Data Migration Example Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Usage‐Examples Demonstrates how to migrate data from an older schema (UserV1) to a newer schema (UserV2) using SignalDB collections and the Tauri file system adapter. It includes creating collections for both versions, iterating through old user data, transforming it, and inserting it into the new collection. ```typescript import { Collection } from '@signaldb/core'; import { createTauriFileSystemAdapter } from '@pitzzahh/signaldb-adapter-tauri'; interface UserV1 { id: string; name: string; email: string; } interface UserV2 { id: string; firstName: string; lastName: string; email: string; createdAt: Date; } class UserMigration { private oldUsers: Collection; private newUsers: Collection; constructor() { this.oldUsers = new Collection({ name: 'users_v1', persistence: createTauriFileSystemAdapter('users_v1.json') }); this.newUsers = new Collection({ name: 'users_v2', persistence: createTauriFileSystemAdapter('users_v2.json') }); } async migrateUsers(): Promise { const oldUsersData = this.oldUsers.find({}); for (const oldUser of oldUsersData) { const [firstName, ...lastNameParts] = oldUser.name.split(' '); const lastName = lastNameParts.join(' ') || ''; const newUser: UserV2 = { id: oldUser.id, firstName, lastName, email: oldUser.email, createdAt: new Date() }; await this.newUsers.insert(newUser); } console.log(`Migrated ${oldUsersData.length} users`); } } // Usage const migration = new UserMigration(); await migration.migrateUsers(); ``` -------------------------------- ### Vue.js Todo App with SignalDB Tauri Persistence Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Quick‐Start A Vue.js component that implements a Todo application with data persistence using the SignalDB Tauri adapter. It showcases adding, toggling, and removing todos, with real-time updates reflected in the UI. ```vue ``` -------------------------------- ### Platform-Specific Considerations: macOS Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Storage‐Configuration Explains macOS-specific storage considerations, such as mapping `BaseDirectory.AppLocalData` to `~/Library/Application Support/` and ensuring adapters are sandbox-safe. ```typescript // macOS-specific storage considerations const macAdapter = createTauriFileSystemAdapter('data.json', { base_dir: BaseDirectory.AppLocalData // Maps to ~/Library/Application Support/ }); // Consider macOS sandbox restrictions const sandboxSafeAdapter = createTauriFileSystemAdapter('data.json', { base_dir: BaseDirectory.AppLocalData // Always safe in sandbox }); ``` -------------------------------- ### Optimize Encryption Operations Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Performance‐Tips Demonstrates how to optimize encryption by using fast hash algorithms for non-sensitive data and appropriate algorithms for sensitive data. It shows examples using Bun.hash and Bun.CryptoHasher. ```typescript import { createTauriFileSystemAdapter } from '@pitzzahh/signaldb-adapter-tauri'; // ✅ Good: Use fast hash algorithms for non-sensitive data const fastAdapter = createTauriFileSystemAdapter('cache.json', { encrypt: async (data) => { // Use fast hash for checksums const hash = Bun.hash(JSON.stringify(data)); return hash.toString(); }, decrypt: async (encrypted) => { // Simple validation (not real encryption) return JSON.parse(encrypted); } }); // ✅ Good: Use appropriate algorithms for sensitive data const secureAdapter = createTauriFileSystemAdapter('sensitive.json', { encrypt: async (data) => { const jsonData = JSON.stringify(data); const hasher = new Bun.CryptoHasher('sha256', 'secret-key'); hasher.update(jsonData); return hasher.digest('hex'); }, decrypt: async (encrypted) => { // Verify and decrypt return JSON.parse(encrypted); } }); ``` -------------------------------- ### Storage Best Practices: Storage Lifecycle Management Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Storage‐Configuration Outlines a `StorageLifecycleManager` class designed to handle the lifecycle of storage adapters. It includes methods for initialization, cleanup of temporary storage, creating backups, and restoring data. ```typescript class StorageLifecycleManager { private adapters: Map = new Map(); async initialize(): Promise { // Initialize all adapters console.log('Initializing storage...'); } async cleanup(): Promise { // Clean up cache files console.log('Cleaning up temporary storage...'); } async backup(): Promise { // Create backups of important data console.log('Creating storage backups...'); } async restore(): Promise { // Restore from backups if needed console.log('Restoring from backups...'); } } ``` -------------------------------- ### Simple Data Storage with SignalDB Tauri Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Usage‐Examples Demonstrates basic data storage using SignalDB's Collection with the Tauri file system adapter. It shows how to insert and find data, with automatic persistence to a JSON file. ```typescript import { Collection } from '@signaldb/core'; import { createTauriFileSystemAdapter } from '@pitzzahh/signaldb-adapter-tauri'; interface User { id: string; name: string; email: string; } // Create a collection with filesystem persistence const users = new Collection({ name: 'users', persistence: createTauriFileSystemAdapter('users.json') }); // Insert data - automatically persisted await users.insert({ id: '1', name: 'John Doe', email: 'john@example.com' }); // Find data const user = users.findOne({ id: '1' }); console.log(user); // { id: '1', name: 'John Doe', email: 'john@example.com' } ``` -------------------------------- ### User Settings Manager with SignalDB and Tauri Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Usage‐Examples Manages user settings using SignalDB collections, persisting data to a JSON file within the application's configuration directory using the Tauri file system adapter. Supports setting, getting, and removing settings by key or category. ```typescript import { Collection } from '@signaldb/core'; import { createTauriFileSystemAdapter } from '@pitzzahh/signaldb-adapter-tauri'; import { BaseDirectory } from '@tauri-apps/plugin-fs'; interface Setting { id: string; key: string; value: any; type: 'string' | 'number' | 'boolean' | 'object'; category: string; updatedAt: Date; } class SettingsManager { private settings: Collection; constructor() { this.settings = new Collection({ name: 'settings', persistence: createTauriFileSystemAdapter('settings.json', { base_dir: BaseDirectory.AppConfig }) }); } async set(key: string, value: T, category: string = 'general'): Promise { const type = typeof value as Setting['type']; const setting: Setting = { id: key, key, value, type, category, updatedAt: new Date() }; const existing = this.settings.findOne({ key }); if (existing) { await this.settings.updateOne({ key }, { $set: setting }); } else { await this.settings.insert(setting); } } get(key: string, defaultValue?: T): T { const setting = this.settings.findOne({ key }); return setting ? setting.value : defaultValue; } getByCategory(category: string): Setting[] { return this.settings.find({ category }); } async remove(key: string): Promise { await this.settings.removeOne({ key }); } async reset(): Promise { await this.settings.removeMany({}); } getAllSettings(): Setting[] { return this.settings.find({}); } } // Usage const settingsManager = new SettingsManager(); await settingsManager.set('theme', 'dark', 'appearance'); await settingsManager.set('autoSave', true, 'editor'); await settingsManager.set('maxRetries', 3, 'network'); const theme = settingsManager.get('theme', 'light'); const autoSave = settingsManager.get('autoSave', false); console.log(`Current theme: ${theme}`); console.log(`Auto-save enabled: ${autoSave}`); ``` -------------------------------- ### Using Base Directories Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Usage‐Examples Shows how to specify different base directories for the Tauri file system adapter when creating SignalDB persistence adapters. This allows organizing data, configuration, and cache files appropriately within the application's file structure. ```typescript // For user data const userData = createTauriFileSystemAdapter('userdata.json', { base_dir: BaseDirectory.AppLocalData }); // For configuration const config = createTauriFileSystemAdapter('config.json', { base_dir: BaseDirectory.AppConfig }); // For cache const cache = createTauriFileSystemAdapter('cache.json', { base_dir: BaseDirectory.AppCache }); ``` -------------------------------- ### TypeScript Type Safety with SignalDB Tauri Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Usage‐Examples Illustrates using TypeScript interfaces with SignalDB collections and the Tauri adapter for enhanced type safety. This example defines a `Task` interface and ensures all data operations adhere to it. ```typescript import { Collection } from '@signaldb/core'; import { createTauriFileSystemAdapter } from '@pitzzahh/signaldb-adapter-tauri'; interface Task { id: string; title: string; completed: boolean; createdAt: Date; tags: string[]; } const tasks = new Collection({ name: 'tasks', persistence: createTauriFileSystemAdapter('tasks.json') }); // Full type safety await tasks.insert({ id: 'task-1', title: 'Learn SignalDB', completed: false, createdAt: new Date(), tags: ['learning', 'database'] }); ``` -------------------------------- ### Linux File System Adapters for Tauri Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Storage‐Configuration Demonstrates creating Tauri file system adapters for Linux, specifying storage locations for application data and configuration files according to common Linux conventions. ```typescript const linuxAdapter = createTauriFileSystemAdapter('data.json', { base_dir: BaseDirectory.AppLocalData // Maps to ~/.local/share/ }); const xdgCompliantConfig = createTauriFileSystemAdapter('config.json', { base_dir: BaseDirectory.AppConfig // Maps to ~/.config/ }); ``` -------------------------------- ### Graceful Error Handling Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Usage‐Examples Provides an example of how to handle errors gracefully when performing operations like inserting data into a SignalDB collection using the Tauri adapter. It demonstrates using a try-catch block to manage potential insertion failures. ```typescript import { Collection } from '@signaldb/core'; import { createTauriFileSystemAdapter } from '@pitzzahh/signaldb-adapter-tauri'; const users = new Collection({ name: 'users', persistence: createTauriFileSystemAdapter('users.json') }); try { await users.insert({ id: '1', name: 'John', email: 'john@example.com' }); } catch (error) { console.error('Failed to insert user:', error); // Handle error appropriately } ``` -------------------------------- ### Tauri Encryption Migration: Adding Encryption Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Migration‐Guide Demonstrates how to add encryption to existing data using the Tauri File System Adapter. Shows the adapter configuration before and after encryption, and provides a migration script to encrypt plain text data. ```typescript // Before (Plain Text) const adapter = createTauriFileSystemAdapter('data.json'); ``` ```typescript // After (Encrypted) const adapter = createTauriFileSystemAdapter('data.json', { encrypt: async (data) => { const hasher = new Bun.CryptoHasher('sha256', 'secret-key'); hasher.update(JSON.stringify(data)); return hasher.digest('hex'); }, decrypt: async (encrypted) => { // Decrypt logic here return JSON.parse(encrypted); } }); ``` ```typescript class EncryptionMigrator { async addEncryptionToExistingData(filename: string, secretKey: string) { // Load plain text data const plainAdapter = createTauriFileSystemAdapter(filename); const data = await plainAdapter.load(); // Create encrypted adapter const encryptedAdapter = createTauriFileSystemAdapter(filename, { encrypt: async (data) => { const hasher = new Bun.CryptoHasher('sha256', secretKey); hasher.update(JSON.stringify(data)); return hasher.digest('hex'); }, decrypt: async (encrypted) => { // Decryption logic return JSON.parse(encrypted); } }); // Save as encrypted await encryptedAdapter.save(data); console.log('Added encryption to existing data'); } } ``` -------------------------------- ### Environment-Based Configuration Storage Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Storage‐Configuration Provides a method to create SignalDB Tauri file system adapters based on the current environment (production, development, testing), dynamically selecting the appropriate base directory. ```typescript import { createTauriFileSystemAdapter } from '@pitzzahh/signaldb-adapter-tauri'; import { BaseDirectory } from '@tauri-apps/plugin-fs'; class EnvironmentStorage { private static getBaseDir(): BaseDirectory { const env = process.env.NODE_ENV || 'development'; switch (env) { case 'production': return BaseDirectory.AppLocalData; case 'development': return BaseDirectory.AppCache; // Easier to clear during development case 'testing': return BaseDirectory.Temp; // Temporary for tests default: return BaseDirectory.AppLocalData; } } static createAdapter(filename: string) { return createTauriFileSystemAdapter(filename, { base_dir: this.getBaseDir() }); } } // Usage const userAdapter = EnvironmentStorage.createAdapter('users.json'); const configAdapter = EnvironmentStorage.createAdapter('config.json'); ``` -------------------------------- ### Default Storage Configuration Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Storage‐Configuration Creates a SignalDB Tauri file system adapter using the default `AppLocalData` directory for storing 'data.json'. ```typescript import { createTauriFileSystemAdapter } from '@pitzzahh/signaldb-adapter-tauri'; // Uses AppLocalData by default const adapter = createTauriFileSystemAdapter('data.json'); ``` -------------------------------- ### Simple Base64 Encryption (Development Only) Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Security‐Guide Demonstrates basic Base64 encoding for data serialization, suitable only for development and testing purposes as it does not provide actual encryption. ```typescript import { createTauriFileSystemAdapter } from '@pitzzahh/signaldb-adapter-tauri'; const adapter = createTauriFileSystemAdapter('data.json', { encrypt: async (data) => btoa(JSON.stringify(data)), decrypt: async (encoded) => JSON.parse(atob(encoded)) }); ``` -------------------------------- ### Schema Migration Test Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Migration‐Guide Provides a test case for schema migrations using the Tauri file system adapter. It sets up old data, runs a schema migration, and verifies the changes in the migrated data. ```typescript import { expect, test } from 'bun:test'; import { createTauriFileSystemAdapter } from '@pitzzahh/signaldb-adapter-tauri'; test('schema migration test', async () => { // Setup old data const adapter = createTauriFileSystemAdapter('migration-test.json'); const oldData = [ { id: '1', name: 'John Doe', email: 'john@example.com' } ]; await adapter.save(oldData); // Run migration const migrator = new SchemaMigrator(); await migrator.migrateUserSchema('migration-test.json'); // Verify migration const newData = await adapter.load(); expect(newData).toHaveLength(1); expect(newData[0]).toHaveProperty('firstName', 'John'); expect(newData[0]).toHaveProperty('lastName', 'Doe'); expect(newData[0]).toHaveProperty('email', 'john@example.com'); }); ``` -------------------------------- ### Custom Base Directory Configuration Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Storage‐Configuration Configures a SignalDB Tauri file system adapter to use a specific base directory, such as `AppConfig`, for storing 'config.json'. ```typescript import { createTauriFileSystemAdapter } from '@pitzzahh/signaldb-adapter-tauri'; import { BaseDirectory } from '@tauri-apps/plugin-fs'; const adapter = createTauriFileSystemAdapter('config.json', { base_dir: BaseDirectory.AppConfig }); ``` -------------------------------- ### Rollback Manager Implementation Source: https://github.com/pitzzahh/signaldb-adapter-tauri/wiki/Migration‐Guide A class for managing data rollbacks. It includes methods to create a backup of a file with a timestamp and to restore a file from a specified backup file. ```typescript class RollbackManager { async createBackup(filename: string): Promise { const timestamp = Date.now(); const backupFilename = `${filename}.backup.${timestamp}`; const originalAdapter = createTauriFileSystemAdapter(filename); const backupAdapter = createTauriFileSystemAdapter(backupFilename); const data = await originalAdapter.load(); await backupAdapter.save(data); return backupFilename; } async rollback(filename: string, backupFilename: string): Promise { const backupAdapter = createTauriFileSystemAdapter(backupFilename); const originalAdapter = createTauriFileSystemAdapter(filename); const backupData = await backupAdapter.load(); await originalAdapter.save(backupData); console.log(`Rolled back ${filename} from ${backupFilename}`); } } ```