Last active
September 4, 2017 14:12
-
-
Save TylerJPresley/6daffd810d6d622729f2da4c5b465079 to your computer and use it in GitHub Desktop.
App storage // Aurelia (CLI/RequireJS)
This file contains hidden or 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
import { Cookie } from './cookie'; | |
import * as moment from 'moment'; | |
import * as store from 'store'; | |
/** | |
* AppStorage class | |
* | |
* @module _resources/app-storage | |
*/ | |
export class AppStorage { | |
public static isLocalAvailable(): boolean { | |
return store.enabled; | |
} | |
/** | |
* Clears all data | |
*/ | |
public static clear(): void { | |
store.clear(); | |
} | |
/** | |
* Gets a value by the key | |
* @param key - key | |
*/ | |
public static get(key: string): any { | |
if (store.enabled) { | |
const payload: any = store.get(key); | |
if (payload && payload.expires && payload.expires >= moment().utc().unix()) { | |
return payload.data; | |
} | |
if (payload && (!payload.hasOwnProperty('expires'))) { | |
AppStorage.set(key, payload, moment().add(1, 'day').toDate().toLocaleString()); | |
return payload; | |
} | |
if (payload && payload.hasOwnProperty('expires') && payload.expires === null) { | |
return payload.data; | |
} | |
return null; | |
} | |
return Cookie.get(key); | |
} | |
/** | |
* Removes a value by the key | |
* @param key - key | |
*/ | |
public static remove(key: string): void { | |
if (store.enabled) { | |
store.remove(key); | |
} else { | |
Cookie.remove(key); | |
} | |
} | |
/** | |
* Sets a value by the key | |
* @param key - key | |
* @param value - value | |
* @param expires - expiration date | |
*/ | |
public static set(key: string, value: any, expires: string): void { | |
if (store.enabled) { | |
const expiration: number = expires ? moment(expires).utc().unix() : null; | |
store.set(key, { | |
data: value, | |
expires: expiration | |
}); | |
} else { | |
Cookie.set(key, value, moment(expires).toDate().toUTCString()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment