Skip to content

Instantly share code, notes, and snippets.

@CVertex
Created January 3, 2017 06:36
Show Gist options
  • Save CVertex/5cfc4e17be809505405d0645ef07cf41 to your computer and use it in GitHub Desktop.
Save CVertex/5cfc4e17be809505405d0645ef07cf41 to your computer and use it in GitHub Desktop.
Storage Typescript adapter layer. Use localStorage when useable, otherwise cookies
namespace Util {
// Contract for storage
export interface Storage {
getItem(key: string): any;
removeItem(key: string): void;
setItem(key: string, data: string): void;
}
// Borrowed from https://gist.github.com/wittnl/2890870
// and a little of https://gist.github.com/remy/350433
class CookieStorage implements Storage {
createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toUTCString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
readCookie(name) {
var result = null;
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEQ) == 0) {
result = c.substring(nameEQ.length, c.length);
return result;
}
}
return result;
}
getItem(key: string): any {
return this.readCookie(key);
}
removeItem(key: string): void {
this.setItem(key, '');
}
setItem(key: string, data: string): void {
if (data != null) {
this.createCookie(key, data, 3000);
}
}
}
// Checks if localStorage is usable
// Borrowed from https://github.com/marcuswestin/store.js/blob/master/src/store.js
// This detects Safari iOS private mode
// see http://apple.stackexchange.com/a/131589
function isLocalStorageUsable() {
try {
var testKey = '__localstoragetest__'
localStorage.setItem(testKey, testKey)
if (localStorage.getItem(testKey) != testKey) {
return false;
}
localStorage.removeItem(testKey)
} catch (e) {
return false;
}
return true;
}
// Loads a concrete Storage
// When localStorage isn't useable, use cookies
export function provideStorageLayer(): Storage {
// Check availability
if (!localStorage) {
return new CookieStorage();
}
// Check safari private mode
if (!isLocalStorageUsable()) {
return new CookieStorage();
}
// Default to localStorage
return localStorage as Storage;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment