Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ashishtilara/0d1df37d367ae2e66640b009c1ab4d0a to your computer and use it in GitHub Desktop.
Save ashishtilara/0d1df37d367ae2e66640b009c1ab4d0a to your computer and use it in GitHub Desktop.
ionic-pouchDb
//copied from http://blog.ionic.io/screencast-ionic-and-sqlite/
.service('DBService', function($q) {
var items;
var db;
var self = this;
this.initDB = function() {
return db = new PouchDB('simpleDB', {
adapter: 'websql'
});
};
this.getDB = function() {
if (!items) {
return $q.when(
db.allDocs({
include_docs: true
}))
.then(function(docs) {
items = docs.rows.map(function(row) {
row.doc.Date = new Date(row.doc.Date);
return row.doc;
});
// Listen for changes on the database.
db.changes({
live: true,
since: 'now',
include_docs: true
})
.on('change', function(change) {
self.onDatabaseChange(change)
});
return items;
});
} else {
return $q.when();
};
};
this.onDatabaseChange = function(change) {
var index = self.findIndex(items, change.id);
var item = items[index];
items.splice(index, 0, change.doc) // insert
}
this.findIndex = function(array, id) {
var low = 0,
high = array.length,
mid;
while (low < high) {
mid = (low + high) >>> 1;
array[mid]._id < id ? low = mid + 1 : high = mid
}
return low;
}
this.storeData = function(data) {
return $q.when(db.post({
'title': data
}))
};
return this
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment