Created
September 16, 2015 14:45
-
-
Save matthewbednarski/5dd19e501409c386fa92 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
(function() { | |
angular | |
.module('mcbPersist', []) | |
.service('persist', ['$q', persistService]); | |
function persistService($q) { | |
var persist = this; | |
this.getDb = function() { | |
if (this.db === undefined) { | |
this.db = new PouchDB("pouchdb"); | |
} | |
return this.db; | |
}; | |
this.remove = function(key) { | |
var defer = $q.defer(); | |
this.getDb().get(key) | |
.then(function(doc) { | |
persist.getDb().remove(doc) | |
.then(defer.resolve) | |
.catch(defer.reject); | |
}) | |
.catch(function(error) { | |
defer.resolve("No doc with id: " + key + ' found'); | |
}); | |
return defer.promise; | |
}; | |
this.store = function(key, obj) { | |
var defer = $q.defer(); | |
var sData = JSON.stringify(obj); | |
this.getDb().get(key) | |
.then(function(doc) { | |
doc.data = sData; | |
persist.getDb().put(doc) | |
.then(defer.resolve) | |
.catch(defer.reject); | |
}) | |
.catch(function(error) { | |
persist.getDb().put({ | |
'_id': key, | |
'data': sData | |
}) | |
.then(defer.resolve) | |
.catch(defer.reject); | |
}); | |
return defer.promise; | |
}; | |
this.retrieve = function(key) { | |
var defer = $q.defer(); | |
this.getDb().get(key) | |
.then(function(doc) { | |
if (doc.hasOwnProperty('data')) { | |
var data = JSON.parse(doc.data); | |
defer.resolve(data); | |
} else { | |
defer.resolve(doc); | |
} | |
}) | |
.catch(function(error) { | |
defer.reject(error); | |
}); | |
return defer.promise; | |
}; | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment