@turnkey/core
Version:
A core JavaScript web and React Native package for interfacing with Turnkey's infrastructure.
73 lines (70 loc) • 3.11 kB
JavaScript
import { SessionKey } from '../../__types__/base.mjs';
import { parseSession } from '../../utils.mjs';
let AsyncStorage;
try {
const mod = require("@react-native-async-storage/async-storage");
AsyncStorage = mod.default ?? mod;
}
catch {
throw new Error("Please install @react-native-async-storage/async-storage in your app to use MobileStorageManager");
}
class MobileStorageManager {
async getStorageValue(sessionKey) {
const item = await AsyncStorage.getItem(sessionKey);
return item ? JSON.parse(item) : undefined;
}
async setStorageValue(sessionKey, storageValue) {
await AsyncStorage.setItem(sessionKey, JSON.stringify(storageValue));
}
async setActiveSessionKey(sessionKey) {
await AsyncStorage.setItem(MobileStorageManager.ACTIVE_SESSION_KEY, sessionKey);
}
async removeStorageValue(sessionKey) {
await AsyncStorage.removeItem(sessionKey);
}
async storeSession(session, sessionKey = SessionKey.DefaultSessionkey) {
const sessionWithMetadata = parseSession(session);
await this.setStorageValue(sessionKey, sessionWithMetadata);
const raw = await this.getStorageValue(MobileStorageManager.ALL_SESSION_KEYS);
const keys = Array.isArray(raw) ? raw : [];
if (!keys.includes(sessionKey)) {
keys.push(sessionKey);
await this.setStorageValue(MobileStorageManager.ALL_SESSION_KEYS, keys);
}
await this.setStorageValue(MobileStorageManager.ACTIVE_SESSION_KEY, sessionKey);
}
async getSession(sessionKey = SessionKey.DefaultSessionkey) {
return this.getStorageValue(sessionKey);
}
async getActiveSessionKey() {
return this.getStorageValue(MobileStorageManager.ACTIVE_SESSION_KEY);
}
async getActiveSession() {
const key = await this.getActiveSessionKey();
return key ? this.getSession(key) : undefined;
}
async listSessionKeys() {
const raw = await this.getStorageValue(MobileStorageManager.ALL_SESSION_KEYS);
return Array.isArray(raw) ? raw : [];
}
async clearSession(sessionKey) {
await this.removeStorageValue(sessionKey);
const keys = await this.listSessionKeys();
const updated = keys.filter((k) => k !== sessionKey);
await this.setStorageValue(MobileStorageManager.ALL_SESSION_KEYS, updated);
const active = await this.getActiveSessionKey();
if (active === sessionKey) {
await this.removeStorageValue(MobileStorageManager.ACTIVE_SESSION_KEY);
}
}
async clearAllSessions() {
const keys = await this.listSessionKeys();
await Promise.all(keys.map((k) => AsyncStorage.removeItem(k)));
await this.removeStorageValue(MobileStorageManager.ALL_SESSION_KEYS);
await this.removeStorageValue(MobileStorageManager.ACTIVE_SESSION_KEY);
}
}
MobileStorageManager.ALL_SESSION_KEYS = "@turnkey/all-session-keys";
MobileStorageManager.ACTIVE_SESSION_KEY = "@turnkey/active-session-key";
export { MobileStorageManager };
//# sourceMappingURL=storage.mjs.map