はじめに
-
パッケージをインストール
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 -
ネイティブプロジェクトと同期
Terminal window npx cap syncTerminal window pnpm cap syncTerminal window yarn cap syncTerminal window bunx cap sync -
プラグインを設定
基本的なストレージの例:
import { CapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';// ストレージデータベースを開くawait CapacitorDataStorageSqlite.openStore({database: 'myapp_storage'});// データを保存await CapacitorDataStorageSqlite.set({key: 'user_preferences',value: JSON.stringify({ theme: 'dark' })});暗号化ストレージの例:
// 暗号化ストレージを開くawait CapacitorDataStorageSqlite.openStore({database: 'secure_storage',encrypted: true,mode: 'encryption'});// 機密データを保存await CapacitorDataStorageSqlite.set({key: 'api_token',value: 'secret_token_value'});iOSでは追加設定は不要です。
Androidでは追加設定は不要です。
-
基本操作
import { CapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';// 値を設定await CapacitorDataStorageSqlite.set({key: 'username',value: 'john_doe'});// 値を取得const { value } = await CapacitorDataStorageSqlite.get({key: 'username'});console.log('Username:', value); // "john_doe"// 値を削除await CapacitorDataStorageSqlite.remove({key: 'username'});// すべてのデータをクリアawait CapacitorDataStorageSqlite.clear();// キーが存在するか確認const { result } = await CapacitorDataStorageSqlite.iskey({key: 'username'});console.log('Key exists:', result); // true or false// すべてのキーを取得const { keys } = await CapacitorDataStorageSqlite.keys();console.log('All keys:', keys);// すべての値を取得const { values } = await CapacitorDataStorageSqlite.values();console.log('All values:', values); -
高度な使用方法
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;// オプション付きでストレージを開くawait CapacitorDataStorageSqlite.openStore({database: this.dbName,encrypted: encrypted,mode: encrypted ? 'encryption' : 'no-encryption',version: 1});}// 汎用ストレージメソッドasync 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;}}// バッチ操作async 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;}// テーブル管理async getTables(): Promise<string[]> {const { tables } = await CapacitorDataStorageSqlite.tables();return tables;}async deleteTable(table: string): Promise<void> {await CapacitorDataStorageSqlite.deleteTable({ table });}// インポート/エクスポート機能async 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> {// 既存データをクリアawait CapacitorDataStorageSqlite.clear();// 新しいデータをインポートfor (const item of data) {await CapacitorDataStorageSqlite.set({key: item.key,value: item.value});}}// フィルタリングと検索async 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;}// 完了時にデータベースを閉じるasync close(): Promise<void> {await CapacitorDataStorageSqlite.closeStore({database: this.dbName});}}// 使用例const storage = new StorageService();await storage.initialize(true); // 暗号化を使用// ユーザーデータを保存await storage.setObject('user_profile', {id: 123,name: 'John Doe',email: 'john@example.com'});// ユーザーデータを取得const profile = await storage.getObject<any>('user_profile');console.log('User profile:', profile);
APIリファレンス
Section titled “APIリファレンス”openStore(options: OpenStoreOptions)
Section titled “openStore(options: OpenStoreOptions)”ストレージデータベースを開きます。
パラメータ:
options.database: string - データベース名options.encrypted: boolean - 暗号化を有効化options.mode: string - ‘encryption’または’no-encryption’options.version: number - データベースバージョン
closeStore(options: CloseStoreOptions)
Section titled “closeStore(options: CloseStoreOptions)”ストレージデータベースを閉じます。
set(options: SetOptions)
Section titled “set(options: SetOptions)”キーバリューペアを保存します。
パラメータ:
options.key: string - ストレージキーoptions.value: string - 保存する値
get(options: GetOptions)
Section titled “get(options: GetOptions)”キーで値を取得します。
戻り値: Promise<{ value: string }>
remove(options: RemoveOptions)
Section titled “remove(options: RemoveOptions)”キーバリューペアを削除します。
clear()
Section titled “clear()”ストレージからすべてのデータをクリアします。
iskey(options: IskeyOptions)
Section titled “iskey(options: IskeyOptions)”キーが存在するか確認します。
戻り値: Promise<{ result: boolean }>
keys()
Section titled “keys()”すべてのストレージキーを取得します。
戻り値: Promise<{ keys: string[] }>
values()
Section titled “values()”すべてのストレージ値を取得します。
戻り値: Promise<{ values: string[] }>
tables()
Section titled “tables()”すべてのテーブル名を取得します。
戻り値: Promise<{ tables: string[] }>
deleteTable(options: DeleteTableOptions)
Section titled “deleteTable(options: DeleteTableOptions)”特定のテーブルを削除します。
インターフェース
Section titled “インターフェース”interface OpenStoreOptions { database: string; encrypted?: boolean; mode?: string; version?: number;}
interface SetOptions { key: string; value: string;}
interface GetOptions { key: string;}
interface RemoveOptions { key: string;}プラットフォーム注意事項
Section titled “プラットフォーム注意事項”- 暗号化用のオプションSQLCipherを備えたSQLite3を使用
- アプリ更新後もデータが保持される
- iOS 11.0+をサポート
Android
Section titled “Android”- オプションSQLCipherを備えたSQLiteを使用
- アプリ更新後もデータが保持される
- Android 5.0 (API 21)+をサポート
一般的な使用例
Section titled “一般的な使用例”- ユーザー設定: アプリの設定と設定を保存
- キャッシュ管理: APIレスポンスとデータをキャッシュ
- オフラインストレージ: オフラインアクセス用にデータを保存
- セッション管理: ユーザーセッションを安全に管理
- トークンストレージ: 認証トークンを安全に保存
ベストプラクティス
Section titled “ベストプラクティス”-
機密データには暗号化を使用
// トークンなどの機密データ用await openStore({database: 'secure_db',encrypted: true,mode: 'encryption'}); -
プレフィックスでキーを整理
// 整理のためにプレフィックスを使用await set({ key: 'user:123:profile', value: userData });await set({ key: 'cache:api:users', value: apiData }); -
大きなデータを慎重に扱う
// 大きなオブジェクトには圧縮を検討const compressed = compress(largeData);await set({ key: 'large_data', value: compressed }); -
定期的なクリーンアップ
// 期限切れのキャッシュエントリを削除const keys = await keys();for (const key of keys.keys) {if (key.startsWith('cache:') && isExpired(key)) {await remove({ key });}}
トラブルシューティング
Section titled “トラブルシューティング”データベースが開かない:
- データベース名が有効か確認 (英数字、アンダースコア)
- データベース名に特殊文字がないことを確認
- 暗号化モードが既存のデータベースと一致することを確認
データが保持されない:
- 操作前に
openStoreが呼ばれていることを確認 - コンソールにエラーがないか確認
- キー名が文字列であることを確認
パフォーマンスの問題:
- 非常に大きな値の保存を避ける
- 可能な場合はバッチ操作を使用
- 異なるデータタイプには複数のデータベースの使用を検討