@turnkey/core
Version:
A core JavaScript web and React Native package for interfacing with Turnkey's infrastructure.
75 lines (71 loc) • 3.15 kB
JavaScript
;
var base = require('../../__types__/base.js');
var utils = require('../../utils.js');
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 = base.SessionKey.DefaultSessionkey) {
const sessionWithMetadata = utils.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 = base.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";
exports.MobileStorageManager = MobileStorageManager;
//# sourceMappingURL=storage.js.map