Skip to content

Instantly share code, notes, and snippets.

@techfort
Created May 12, 2015 10:15
Show Gist options
  • Save techfort/a5f35450fb13c771a506 to your computer and use it in GitHub Desktop.
Save techfort/a5f35450fb13c771a506 to your computer and use it in GitHub Desktop.
angular.module('myapp')
.service('LocalDatabase', ['$rootScope', '$window', 'LOCAL_DB', function ($rootScope, $window, LOCAL_DB) {
var filesystem, db = new loki('mydb'), user, users, coupons;
$window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, obtainedFS, fail);
function obtainedFS(fs) {
filesystem = fs;
loadDatabase();
}
function fail(evt) {
console.log(JSON.stringify(evt));
}
function loadDatabase() {
filesystem.root.getFile(LOCAL_DB, null,
function () {
db.loadDatabase(LOCAL_DB);
},
createFile);
}
function createFile() {
filesystem.root.getFile(LOCAL_DB, {create: true},
function () {
console.log('File {0} created', LOCAL_DB);
},
fail);
}
// initialize users collection or create it if it doesn't exist
try {
users = db.getCollection('users');
} catch (e) {
db.addCollection('users', { indices: ['id'] });
users = db.getCollection('users');
}
try {
db.removeCollection('coupons');
} catch (err) {
}
coupons = db.addCollection('coupons', 'Coupon');
coupons.insert({'title': 'Wagner\'s Opera Omnia', 'percentage': '25%', 'description': 'The complete works of Richard Wagner in one boxset' });
coupons.insert({'title': 'Heavy Metal is the Law', 'percentage': '25%', 'description': 'Very misleading title for a book on steel works'});
coupons.insert({'title': 'C++ Programming', 'percentage': '15%', 'description': 'Reference book for programming in c++'});
// Public API
return {
setUser: function (username) {
if (users.data.length > 0) {
user = users.get(1);
user.username = username;
} else {
users.insert({"username": username});
}
user = users.get(1);
},
getUser: function () {
return user;
},
getCoupons: function () {
return coupons.find();
},
insertCoupon: function (c) {
coupons.insert(c);
},
getCollection: function (name) {
return db.getCollection(name);
}
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment