Getting Started
此内容尚不支持你的语言。
-
Install the package
Terminal window npm i @capgo/capacitor-data-storage-sqliteTerminal window pnpm add @capgo/capacitor-data-storage-sqliteTerminal window yarn add @capgo/capacitor-data-storage-sqliteTerminal window bun add @capgo/capacitor-data-storage-sqlite -
Sync with native projects
Terminal window npx cap syncTerminal window pnpm cap syncTerminal window yarn cap syncTerminal window bunx cap sync -
Configure the plugin
Basic Storage Example:
import { CapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';// Open a storage databaseawait CapacitorDataStorageSqlite.openStore({database: 'myapp_storage'});// Store dataawait CapacitorDataStorageSqlite.set({key: 'user_preferences',value: JSON.stringify({ theme: 'dark' })});Encrypted Storage Example:
// Open encrypted storageawait CapacitorDataStorageSqlite.openStore({database: 'secure_storage',encrypted: true,mode: 'encryption'});// Store sensitive dataawait CapacitorDataStorageSqlite.set({key: 'api_token',value: 'secret_token_value'});No additional setup required for iOS.
No additional setup required for Android.
-
Basic operations
import { CapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';// Set a valueawait CapacitorDataStorageSqlite.set({key: 'username',value: 'john_doe'});// Get a valueconst { value } = await CapacitorDataStorageSqlite.get({key: 'username'});console.log('Username:', value); // "john_doe"// Remove a valueawait CapacitorDataStorageSqlite.remove({key: 'username'});// Clear all dataawait CapacitorDataStorageSqlite.clear();// Check if key existsconst { result } = await CapacitorDataStorageSqlite.iskey({key: 'username'});console.log('Key exists:', result); // true or false// Get all keysconst { keys } = await CapacitorDataStorageSqlite.keys();console.log('All keys:', keys);// Get all valuesconst { values } = await CapacitorDataStorageSqlite.values();console.log('All values:', values); -
Advanced usage
import { CapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';export class StorageService {private dbName = 'app_storage';private isEncrypted = false;async initialize(encrypted = false) {this.isEncrypted = encrypted;// Open storage with optionsawait CapacitorDataStorageSqlite.openStore({database: this.dbName,encrypted: encrypted,mode: encrypted ? 'encryption' : 'no-encryption',version: 1});}// Generic storage methodsasync setObject<T>(key: string, data: T): Promise<void> {const value = JSON.stringify(data);await CapacitorDataStorageSqlite.set({ key, value });}async getObject<T>(key: string): Promise<T | null> {try {const { value } = await CapacitorDataStorageSqlite.get({ key });return value ? JSON.parse(value) : null;} catch (error) {console.error('Error getting object:', error);return null;}}// Batch operationsasync setMultiple(items: Record<string, any>): Promise<void> {for (const [key, value] of Object.entries(items)) {await CapacitorDataStorageSqlite.set({key,value: typeof value === 'string' ? value : JSON.stringify(value)});}}async getMultiple(keys: string[]): Promise<Record<string, any>> {const results: Record<string, any> = {};for (const key of keys) {try {const { value } = await CapacitorDataStorageSqlite.get({ key });results[key] = value;} catch (error) {results[key] = null;}}return results;}// Table managementasync getTables(): Promise<string[]> {const { tables } = await CapacitorDataStorageSqlite.tables();return tables;}async deleteTable(table: string): Promise<void> {await CapacitorDataStorageSqlite.deleteTable({ table });}// Import/Export functionalityasync exportToJson(): Promise<any[]> {const { keys } = await CapacitorDataStorageSqlite.keys();const { values } = await CapacitorDataStorageSqlite.values();return keys.map((key, index) => ({key,value: values[index]}));}async importFromJson(data: Array<{ key: string; value: string }>): Promise<void> {// Clear existing dataawait CapacitorDataStorageSqlite.clear();// Import new datafor (const item of data) {await CapacitorDataStorageSqlite.set({key: item.key,value: item.value});}}// Filtering and searchingasync keysStartingWith(prefix: string): Promise<string[]> {const { keys } = await CapacitorDataStorageSqlite.keys();return keys.filter(key => key.startsWith(prefix));}async filterByPrefix(prefix: string): Promise<Array<{ key: string; value: string }>> {const { keys } = await CapacitorDataStorageSqlite.keys();const { values } = await CapacitorDataStorageSqlite.values();const filtered: Array<{ key: string; value: string }> = [];keys.forEach((key, index) => {if (key.startsWith(prefix)) {filtered.push({ key, value: values[index] });}});return filtered;}// Close database when doneasync close(): Promise<void> {await CapacitorDataStorageSqlite.closeStore({database: this.dbName});}}// Usage exampleconst storage = new StorageService();await storage.initialize(true); // Use encryption// Store user dataawait storage.setObject('user_profile', {id: 123,name: 'John Doe',email: 'john@example.com'});// Retrieve user dataconst profile = await storage.getObject<any>('user_profile');console.log('User profile:', profile);
API Reference
Methods
openStore(options: OpenStoreOptions)
Open a storage database.
Parameters:
options.database
: string - Database nameoptions.encrypted
: boolean - Enable encryptionoptions.mode
: string - ‘encryption’ or ‘no-encryption’options.version
: number - Database version
closeStore(options: CloseStoreOptions)
Close the storage database.
set(options: SetOptions)
Store a key-value pair.
Parameters:
options.key
: string - Storage keyoptions.value
: string - Value to store
get(options: GetOptions)
Retrieve a value by key.
Returns: Promise<{ value: string }>
remove(options: RemoveOptions)
Remove a key-value pair.
clear()
Clear all data from storage.
iskey(options: IskeyOptions)
Check if a key exists.
Returns: Promise<{ result: boolean }>
keys()
Get all storage keys.
Returns: Promise<{ keys: string[] }>
values()
Get all storage values.
Returns: Promise<{ values: string[] }>
tables()
Get all table names.
Returns: Promise<{ tables: string[] }>
deleteTable(options: DeleteTableOptions)
Delete a specific table.
Interfaces
interface OpenStoreOptions { database: string; encrypted?: boolean; mode?: string; version?: number;}
interface SetOptions { key: string; value: string;}
interface GetOptions { key: string;}
interface RemoveOptions { key: string;}
Platform Notes
iOS
- Uses SQLite3 with optional SQLCipher for encryption
- Data persists across app updates
- Supports iOS 11.0+
Android
- Uses SQLite with optional SQLCipher
- Data persists across app updates
- Supports Android 5.0 (API 21)+
Common Use Cases
- User Preferences: Store app settings and preferences
- Cache Management: Cache API responses and data
- Offline Storage: Store data for offline access
- Session Management: Manage user sessions securely
- Token Storage: Securely store authentication tokens
Best Practices
-
Use Encryption for Sensitive Data
// For sensitive data like tokensawait openStore({database: 'secure_db',encrypted: true,mode: 'encryption'}); -
Organize Keys with Prefixes
// Use prefixes for organizationawait set({ key: 'user:123:profile', value: userData });await set({ key: 'cache:api:users', value: apiData }); -
Handle Large Data Carefully
// For large objects, consider compressionconst compressed = compress(largeData);await set({ key: 'large_data', value: compressed }); -
Regular Cleanup
// Remove expired cache entriesconst keys = await keys();for (const key of keys.keys) {if (key.startsWith('cache:') && isExpired(key)) {await remove({ key });}}
Troubleshooting
Database not opening:
- Check database name is valid (alphanumeric, underscores)
- Ensure no special characters in database name
- Verify encryption mode matches existing database
Data not persisting:
- Ensure
openStore
is called before operations - Check for any errors in console
- Verify key names are strings
Performance issues:
- Avoid storing very large values
- Use batch operations when possible
- Consider using multiple databases for different data types