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 options
await CapacitorDataStorageSqlite.openStore({
mode: encrypted ? 'encryption' : 'no-encryption',
// Generic storage methods
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> {
const { value } = await CapacitorDataStorageSqlite.get({ key });
return value ? JSON.parse(value) : null;
console.error('Error getting object:', error);
async setMultiple(items: Record<string, any>): Promise<void> {
for (const [key, value] of Object.entries(items)) {
await CapacitorDataStorageSqlite.set({
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) {
const { value } = await CapacitorDataStorageSqlite.get({ key });
async getTables(): Promise<string[]> {
const { tables } = await CapacitorDataStorageSqlite.tables();
async deleteTable(table: string): Promise<void> {
await CapacitorDataStorageSqlite.deleteTable({ table });
// Import/Export functionality
async exportToJson(): Promise<any[]> {
const { keys } = await CapacitorDataStorageSqlite.keys();
const { values } = await CapacitorDataStorageSqlite.values();
return keys.map((key, index) => ({
async importFromJson(data: Array<{ key: string; value: string }>): Promise<void> {
await CapacitorDataStorageSqlite.clear();
for (const item of data) {
await CapacitorDataStorageSqlite.set({
// Filtering and searching
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] });
// Close database when done
async close(): Promise<void> {
await CapacitorDataStorageSqlite.closeStore({
const storage = new StorageService();
await storage.initialize(true); // Use encryption
await storage.setObject('user_profile', {
email: 'john@example.com'
const profile = await storage.getObject<any>('user_profile');
console.log('User profile:', profile);