Skip to content

Instantly share code, notes, and snippets.

@teebot
Last active August 29, 2015 14:14
Show Gist options
  • Save teebot/88dc421e860e60195f97 to your computer and use it in GitHub Desktop.
Save teebot/88dc421e860e60195f97 to your computer and use it in GitHub Desktop.
Angular LocalStorage Key Value Store
angular.factory 'userPrefsService', (localStorageService) ->
STORAGE_KEY = 'userPrefs'
userPrefs = localStorageService.get(STORAGE_KEY) || {}
return {
set: (key, obj) ->
if !key? || key.length == 0
throw new Error('A key is required to store a value in the store')
if obj == null
delete userPrefs[key]
else
userPrefs[key] = obj
localStorageService.set(STORAGE_KEY, angular.toJson(userPrefs))
get: (key) ->
if !key? || key.length == 0
throw new Error('A key is required to retrieve a value from the store')
if !localStorageService.get(STORAGE_KEY)?
return null
return angular.fromJson(localStorageService.get(STORAGE_KEY))[key]
}
describe 'user preferences service', ->
userPrefsService = null
beforeEach(module('LocalStorageModule'))
beforeEach(inject( (_userPrefsService_) ->
userPrefsService = _userPrefsService_
))
it 'should store and retrieve a string value by key', ->
userPrefsService.set('hobby', 'tennis')
storedVal = userPrefsService.get('hobby')
expect(storedVal).toEqual('tennis')
it 'should append new properties by key', ->
userPrefsService.set('hobby', 'tennis')
userPrefsService.set('job', 'cook')
storedValHobby = userPrefsService.get('hobby')
storedValJob = userPrefsService.get('job')
expect(storedValHobby).toEqual('tennis')
expect(storedValJob).toEqual('cook')
it 'should store and retrieve an array by key', ->
userPrefsService.set('beatles', [{ id: 1, name: 'John' }, { id: 2, name: 'Paul' }])
storedVal = userPrefsService.get('beatles')
expect(storedVal[1].id).toEqual(2)
expect(storedVal[0].name).toEqual('John')
it 'should store and retrieve an array by key', ->
storedVal = userPrefsService.get('ramones')
expect(storedVal).not.toBeDefined()
it 'should update an existing value', ->
userPrefsService.set('hobby', 'tennis')
userPrefsService.set('hobby', 'soccer')
storedVal = userPrefsService.get('hobby')
expect(storedVal).toEqual('soccer')
it 'should throw an error when trying to retrieve a value without key', ->
expect(-> userPrefsService.get()).toThrow(new Error('A key is required to retrieve a value from the store'))
it 'should throw an error when trying to store a value without key', ->
expect(-> userPrefsService.set()).toThrow(new Error('A key is required to store a value in the store'))
it 'should be able to remove a key', ->
userPrefsService.set('hobby', 'tennis')
userPrefsService.set('hobby', null)
storedVal = userPrefsService.get('hobby')
expect(storedVal).toBeUndefined()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment