Skip to content

Instantly share code, notes, and snippets.

@pwfisher
Last active April 20, 2021 19:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pwfisher/6f2bf47032b6d5ae92ec1756e0ed96e7 to your computer and use it in GitHub Desktop.
Save pwfisher/6f2bf47032b6d5ae92ec1756e0ed96e7 to your computer and use it in GitHub Desktop.
Ember service:local-storage trivial wrapper for window.localStorage
import { moduleFor } from 'ember-qunit'
import test from 'dummy/tests/ember-sinon-qunit/test'
moduleFor('service:local-storage')
const mockStore = { setItem() { }, removeItem() { } }
test('when localStorage throws an exception', function testCatch(assert) {
const service = this.subject()
const stub = this.stub(mockStore, 'setItem').throws()
service.localStorage = mockStore
service.length()
assert.ok(stub.called, 'the exception is caught')
})
test('when localStorage is used', function testStorage(assert) {
const service = this.subject()
service.removeItem('foo') // ensure setting 'foo' increases length
const startLength = service.length()
service.setItem('foo', 'bar')
assert.equal(service.getItem('foo'), 'bar', 'setItem stores a value by key and getItem gets it')
assert.equal(service.length(), startLength + 1, 'setting an item increases the length')
assert.ok(service.key(0), 'items can be fetched by key index')
service.removeItem('foo')
assert.equal(service.length(), startLength, 'removing an item decreases the length')
})
import Ember from 'ember'
/**
* Wraps window.localStorage and adds convenience property isSupported.
* https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage
*/
export default Ember.Service.extend({
init() {
try {
this.localStorage = window.localStorage // test hook
} catch (e) {
this.localStorage = null
}
},
isSupported: Ember.computed(function isSupported() {
const uid = new Date()
try {
this.localStorage.setItem(uid, uid)
this.localStorage.removeItem(uid)
return true
} catch (e) {
return false
}
}),
getItem(...args) {
return this.get('isSupported') && this.localStorage.getItem(...args)
},
key(...args) {
return this.get('isSupported') && this.localStorage.key(...args)
},
length() {
return this.get('isSupported') && this.localStorage.length
},
removeItem(...args) {
return this.get('isSupported') && this.localStorage.removeItem(...args)
},
setItem(...args) {
return this.get('isSupported') && this.localStorage.setItem(...args)
},
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment