Skip to content

Instantly share code, notes, and snippets.

@lafiosca
Created November 6, 2019 01:12
Show Gist options
  • Save lafiosca/774fa014d3326fcc992b55198ac5ea1d to your computer and use it in GitHub Desktop.
Save lafiosca/774fa014d3326fcc992b55198ac5ea1d to your computer and use it in GitHub Desktop.
TypeScript Amplify Auth storage module for pre-emptive upgrade to @react-native-community/async-storage
import AsyncStorage from '@react-native-community/async-storage';
const memoryKeyPrefix = '@MemoryStorage:';
interface MemoryData {
[key: string]: string;
}
export default class AmplifyCommunityAsyncStorage {
static memoryData: MemoryData = {};
static syncPromise: Promise<void> | undefined;
static setItem = (key: string, value: string) => {
AsyncStorage.setItem(`${memoryKeyPrefix}${key}`, value)
.catch((error) => {
console.error(`Failed to set item ${key} in AsyncStorage: ${error}`);
});
AmplifyCommunityAsyncStorage.memoryData[key] = value;
return value;
};
static getItem = (key: string) => {
const value = AmplifyCommunityAsyncStorage.memoryData[key];
return value === undefined ? null : value;
};
static removeItem = (key: string) => {
AsyncStorage.removeItem(`${memoryKeyPrefix}${key}`)
.catch((error) => {
console.error(`Failed to remove item ${key} in AsyncStorage: ${error}`);
});
delete AmplifyCommunityAsyncStorage.memoryData[key];
};
static clear = () => {
AsyncStorage.multiRemove(Object.keys(AmplifyCommunityAsyncStorage.memoryData))
.catch((error) => {
console.error(`Failed to clear memoryData items from AsyncStorage: ${error}`);
});
AmplifyCommunityAsyncStorage.memoryData = {};
};
static createSyncPromise = async () => {
AmplifyCommunityAsyncStorage.memoryData = {};
const keys = await AsyncStorage.getAllKeys();
const memoryKeys = keys.filter((key) => key.startsWith(memoryKeyPrefix));
const pairs = await AsyncStorage.multiGet(memoryKeys);
pairs.forEach(([memoryKey, value]) => {
if (value) {
const key = memoryKey.replace(memoryKeyPrefix, '');
AmplifyCommunityAsyncStorage.memoryData[key] = value;
}
});
};
static sync = () => {
if (!AmplifyCommunityAsyncStorage.syncPromise) {
console.log('Sync items from AsyncStorage to memoryData');
AmplifyCommunityAsyncStorage.syncPromise = AmplifyCommunityAsyncStorage.createSyncPromise();
}
return AmplifyCommunityAsyncStorage.syncPromise;
};
}
import Auth from '@aws-amplify/auth';
import AmplifyCommunityAsyncStorage from './AmplifyCommunityAsyncStorage';
Auth.configure({
Auth: {
identityPoolId: 'us-east-1:xxxxx',
region: 'us-east-1',
userPoolId: 'us-east-1_xxxxx',
userPoolWebClientId: 'xxxxx',
storage: AmplifyCommunityAsyncStorage,
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment