This commit is contained in:
2018-05-03 15:07:59 -04:00
commit e21c8a23de
14 changed files with 200 additions and 0 deletions

1
src/index.ts Normal file
View File

@ -0,0 +1 @@
export * from './webStorage';

34
src/webStorage.ts Normal file
View File

@ -0,0 +1,34 @@
import {AES, enc} from 'crypto-js';
export interface WebStorageOptions {
fieldName?: string;
encryptionKey?: string;
defaultValue?: any;
}
export function LocalStorage(opts: WebStorageOptions = {}) {
return storage(localStorage, opts);
}
export function SessionStorage(opts: WebStorageOptions = {}) {
return storage(sessionStorage, opts);
}
function storage(storageType: Storage, opts: WebStorageOptions = {}) {
return function(target: object, key: string) {
if(!opts.fieldName) opts.fieldName = key;
Object.defineProperty(target, key, {
get: function() {
let value = storageType.getItem(<string>opts.fieldName);
if(!value && opts.defaultValue != null) return opts.defaultValue;
if(value != null && opts.encryptionKey) value = AES.decrypt(JSON.parse(value), opts.encryptionKey).toString(enc.Utf8);
return JSON.parse(<string>value);
},
set: function(value) {
if(value != null && opts.encryptionKey) value = AES.encrypt(JSON.stringify(value), opts.encryptionKey).toString();
storageType.setItem(<string>opts.fieldName, JSON.stringify(value));
}
});
};
}