Skip to content

Commit

Permalink
feat(core): support persistence of state with camelCase props in the …
Browse files Browse the repository at this point in the history
…local storage
  • Loading branch information
tomastrajan committed Sep 16, 2018
1 parent d4f1d68 commit 2763f1b
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 13 deletions.
42 changes: 35 additions & 7 deletions src/app/core/local-storage/local-storage.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,46 @@
import { TestBed, inject } from '@angular/core/testing';
import { TestBed } from '@angular/core/testing';

import { LocalStorageService } from './local-storage.service';

describe('LocalStorageService', () => {
let service: LocalStorageService;

beforeEach(() => {
TestBed.configureTestingModule({
providers: [LocalStorageService]
});
service = TestBed.get(LocalStorageService);
});

afterEach(() => localStorage.clear());

it('should be created', () => {
expect(service).toBeTruthy();
});

it('should get and set the item', () => {
service.setItem('TEST', 'item');
expect(service.getItem('TEST')).toBe('item');
});

it('should load initial state', () => {
service.setItem('TEST.PROP', 'value');
expect(LocalStorageService.loadInitialState()).toEqual({
test: { prop: 'value' }
});
});

it(
'should be created',
inject([LocalStorageService], (service: LocalStorageService) => {
expect(service).toBeTruthy();
})
);
it('should load nested initial state', () => {
service.setItem('TEST.PROP1.PROP2', 'value');
expect(LocalStorageService.loadInitialState()).toEqual({
test: { prop1: { prop2: 'value' } }
});
});

it('should load nested initial state with camel case properties and object value', () => {
service.setItem('TEST.PROP.SUB-PROP', 'value');
expect(LocalStorageService.loadInitialState()).toEqual({
test: { prop: { subProp: 'value' } }
});
});
});
22 changes: 16 additions & 6 deletions src/app/core/local-storage/local-storage.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,24 @@ export class LocalStorageService {
static loadInitialState() {
return Object.keys(localStorage).reduce((state: any, storageKey) => {
if (storageKey.includes(APP_PREFIX)) {
state = state || {};
const stateKey = storageKey
const stateKeys = storageKey
.replace(APP_PREFIX, '')
.toLowerCase()
.split('.');
.split('.')
.map(key =>
key
.split('-')
.map(
(token, index) =>
index === 0
? token
: token.charAt(0).toUpperCase() + token.slice(1)
)
.join('')
);
let currentStateRef = state;
stateKey.forEach((key, index) => {
if (index === stateKey.length - 1) {
stateKeys.forEach((key, index) => {
if (index === stateKeys.length - 1) {
currentStateRef[key] = JSON.parse(localStorage.getItem(storageKey));
return;
}
Expand All @@ -25,7 +35,7 @@ export class LocalStorageService {
});
}
return state;
}, undefined);
}, {});
}

setItem(key: string, value: any) {
Expand Down

0 comments on commit 2763f1b

Please sign in to comment.