Skip to content

Instantly share code, notes, and snippets.

@sofyan-ahmad
Last active February 3, 2021 06:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sofyan-ahmad/5d6727f7fddb7886583b16970367e10c to your computer and use it in GitHub Desktop.
Save sofyan-ahmad/5d6727f7fddb7886583b16970367e10c to your computer and use it in GitHub Desktop.
AWS Amplify Custom Asyncstorage
import {Auth} from 'aws-amplify';
import AsyncStorage from '@react-native-community/async-storage';
import {ICognitoStorage} from 'amazon-cognito-identity-js';
const MEMORY_KEY_PREFIX = '@fcAuth:';
let dataMemory = {};
const syncPromise: Promise<any> = null;
/**
* This is used to set a specific item in storage
*/
function setItem(key: string, value: any) {
AsyncStorage.setItem(MEMORY_KEY_PREFIX + key, value);
dataMemory[key] = value;
return dataMemory[key];
}
/**
* This is used to get a specific key from storage
*/
function getItem(key: string) {
return Object.prototype.hasOwnProperty.call(dataMemory, key)
? dataMemory[key]
: undefined;
}
/**
* This is used to remove an item from storage
*/
function removeItem(key: string) {
AsyncStorage.removeItem(MEMORY_KEY_PREFIX + key);
return delete dataMemory[key];
}
/**
* This is used to clear the storage
*/
function clear() {
dataMemory = {};
return dataMemory;
}
/**
* Will sync the MemoryStorage data from AsyncStorage to storageWindow MemoryStorage
*/
async function sync() {
if (!syncPromise) {
try {
// syncPromise = new Promise((res, rej) => {
const keys = await AsyncStorage.getAllKeys();
const memoryKeys = keys.filter((key: string) =>
key.startsWith(MEMORY_KEY_PREFIX),
);
const stores: string[][] = await AsyncStorage.multiGet(memoryKeys);
stores.map((store: string[]) => {
const key = store[0];
const value = store[1];
const memoryKey = key.replace(MEMORY_KEY_PREFIX, '');
dataMemory[memoryKey] = value;
});
} catch (err) {
console.error(err);
}
}
return syncPromise;
}
export const AuthStorage: ICognitoStorage & {sync: () => Promise<any>} = {
setItem,
getItem,
removeItem,
clear,
sync,
};
Auth.configure({
storage: AuthStorage,
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment