Skip to content

Instantly share code, notes, and snippets.

@jdnichollsc
Last active January 26, 2016 10:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdnichollsc/f82592d6f303aaebfb9f to your computer and use it in GitHub Desktop.
Save jdnichollsc/f82592d6f303aaebfb9f to your computer and use it in GitHub Desktop.
PouchDB with SQLite plugin in Ionic Framework (Pre-populated database) => Using service pattern
controllers.controller('DocsController', ['$scope', '$ionicPlatform', 'Docs', 'Products' function ($scope, $ionicPlatform, Docs, Products) {
$scope.products = [];
$scope.allDocs = [];
$ionicPlatform.ready(function () {
//Insert a new product
Products.addProduct({
name : 'Milk',
price : 2000
}).then(function () {
//Get Products
return Products.getProducts();
}).then(function (products) {
$scope.products = products.rows;
//Get All Docs
return Docs.getDocs();
}).then(function (docs) {
$scope.allDocs = docs.rows;
alert("Total Docs: " + docs.total_rows);
}).catch(function (err) {
console.log(err);
});
});
} ]);
services.factory('Docs', function ($q, pouchService) {
return {
getDocs: function () {
return $q.when(pouchService.db().allDocs({ include_docs: true }));
}
};
});
services.service('pouchService', function () {
var _db;
this.db = function () {
if (!_db) {
_db = new PouchDB('demoDB', { adapter: 'websql', createFromLocation: 1, androidDatabaseImplementation: 2 });
if (!_db.adapter) {
console.log("SQLite no fue soportado por PouchDB");
_db = new PouchDB('demoDB');
}
_db.info().then(console.log.bind(console)); //return sqlite_plugin: true
}
return _db;
};
});
services.factory('Products', function ($q, pouchService) {
var type = 'product';
return {
getProducts: function () {
return $q.when(pouchService.db().query(productMapFunction, { include_docs: true }));
},
addProduct: function (product) {
product.type = type;
return $q.when(pouchService.db().post(product));
}
};
function productMapFunction(doc, emit) {
if (doc.type === type) {
emit(doc);
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment