Created
November 1, 2019 04:29
-
-
Save mfcodeworks/cb6309dfee5bdf4bba206e4af2c598d2 to your computer and use it in GitHub Desktop.
Encrypted storage with localforage.js typescript version
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
// Declare for typescript | |
declare var CryptoJS: any; | |
declare var localforage: any; | |
// Constants | |
const passphrase = 'A3PnGzWjxGuAYtFu', | |
key = 'data', | |
object = { foo: 'bar' }; | |
// Log original item | |
console.log('Original object', object); | |
// Store item with encryption | |
setItem(key, object, passphrase) | |
.then(data => console.log('Set item response', data)) | |
.catch(err => console.warn('Set item error', err)); | |
// Log retrieved item | |
getItem(key, passphrase) | |
.then(data => console.log('Returned object', data)) | |
.catch(err => console.warn('Get item error', err)); | |
// Set object in storage | |
function setItem(key: string, data: any, passphrase?: string): Promise<any> { | |
// If passphrase is present, JSON stringify and encrypt string | |
if (passphrase) { | |
console.log('Encrypting data'); | |
data = CryptoJS.AES.encrypt(JSON.stringify(data), passphrase).toString(); | |
console.log('Encrypted data', data); | |
} | |
return localforage.setItem(key, data); | |
} | |
// Get object from storage | |
function getItem(key: string, passphrase?: string): Promise<any> { | |
return localforage.getItem(key) | |
.then(data => { | |
// If passphrase is present, decrypt string and parse JSON | |
if (passphrase) { | |
console.log('Data encrypted, decrypting'); | |
data = CryptoJS.AES.decrypt(data, passphrase); | |
console.log('Decrypted data encoded', data); | |
data = data.toString(CryptoJS.enc.Utf8) | |
console.log('Decrypted data decoded', data); | |
return JSON.parse(data); | |
} | |
return data; | |
}); | |
} | |
// Delete object from storage | |
function deleteItem(key: string): Promise<any> { | |
return localforage.removeItem(key); | |
} | |
// Clear storage | |
function deleteAll(): Promise<any> { | |
return localforage.clear(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment