Skip to content

Instantly share code, notes, and snippets.

@ursm
Last active August 29, 2015 14:15
Embed
What would you like to do?
`import Ember from 'ember'`
`import Session from 'simple-auth/session'`
makePromise = (promiseOrValue) ->
if promiseOrValue.then
promiseOrValue
else
Ember.RSVP.resolve(promiseOrValue)
AsyncSession = Session.extend
restore: ->
new Ember.RSVP.Promise (resolve, reject) =>
makePromise(@store.restore()).then (restoredContent) =>
authenticator = restoredContent.authenticator
if !!authenticator
delete restoredContent.authenticator
@container.lookup(authenticator).restore(restoredContent).then (content) =>
@setup authenticator, content
do resolve
, =>
do @store.clear
do reject
else
do @store.clear
do reject
, reject
`export default AsyncSession`
import Ember from 'ember';
import Base from 'simple-auth/stores/base';
import objectsAreEqual from 'simple-auth/utils/objects-are-equal';
export default Base.extend({
key: 'ember_simple_auth:session',
sync: false,
init: function() {
this.storage = this.sync ? chrome.storage.sync : chrome.storage.local;
this.bindToStorageEvents();
},
persisit: function(data) {
var _this = this;
var payload = {};
payload[this.key] = JSON.stringify(data || {});
this.storage.set(payload, function() {
_this.restore().then(function(restoredData) {
_this._lastData = restoredData;
});
});
},
restore: function() {
var _this = this;
return new Ember.RSVP.Promise(function(resolve) {
_this.storage.get(_this.key, function(payload) {
resolve(JSON.parse(payload[_this.key]) || {});
});
});
},
clear: function() {
this.storage.remove(this.key);
this._lastData = {};
},
bindToStorageEvents: function() {
var _this = this;
chrome.storage.onChanged.addListener(function() {
_this.restore().then(function(data) {
if (!objectsAreEqual(data, _this.lastData)) {
_this._lastData = data;
_this.trigger('sessionDataUpdated', data);
}
});
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment