Created
October 27, 2020 10:42
-
-
Save jeremycastelli/487a3f5f215c193b67f4e0a123fecd8b to your computer and use it in GitHub Desktop.
vuex persist capacitor SQLite storage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// store/index.ts | |
import VuexPersistence, { AsyncStorage } from 'vuex-persist'; | |
import { useStorage } from '@/composables/Storage'; | |
// ... | |
const storage = useStorage(); | |
const vuexPersist = new VuexPersistence<RootState>({ | |
asyncStorage: true, | |
strictMode: false, | |
storage: (storage as AsyncStorage) | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Plugins } from '@capacitor/core'; | |
import 'capacitor-data-storage-sqlite'; | |
export function useStorage(options: any = {}) { | |
const { CapacitorDataStorageSqlite } = Plugins; | |
const storage: any = CapacitorDataStorageSqlite; | |
let opened = false; | |
const openStorage = async (): Promise<boolean> => { | |
if (opened) { return true; } | |
const { result } = await storage.openStore(options); | |
opened = result; | |
return result; | |
} | |
const setItem = async (key: string, value: any): Promise<void> => { | |
await openStorage(); | |
await storage.set({ key, value: JSON.stringify(value) }); | |
return; | |
} | |
const getItem = async (key: string): Promise<any> => { | |
await openStorage(); | |
const { value } = await storage.get({ key }); | |
return JSON.parse(value); | |
} | |
const getAllKeys = async (): Promise<string[]> => { | |
await openStorage(); | |
const { keys } = await storage.keys(); | |
return keys; | |
} | |
const length = async (): Promise<number> => { | |
return (await getAllKeys()).length; | |
} | |
const key = async (value: number): Promise<string> => { | |
return (await getAllKeys())[value]; | |
} | |
const removeItem = async (key: string): Promise<void> => { | |
await openStorage(); | |
await storage.remove({ key }); | |
return; | |
} | |
const clear = async (): Promise<void> => { | |
await openStorage(); | |
await storage.clear(); | |
return; | |
} | |
return { | |
openStorage, | |
setItem, | |
getItem, | |
getAllKeys, | |
length, | |
key, | |
removeItem, | |
clear | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment