Reputation: 6438
In using IndexedDB within AngularJS, I have this dilemma, as described in title, and not sure what would be the right way to go about it.
In many tutorials, database is being opened once, and that's it, all methods use that one connection.
In one AngularJS specific example, database opening request, as well as all CRUD methods are wrapped in a factory, and the controller as soon as it loads, calls the open method, and all CRUD methods are in this one controller.
I understood it's a good practice to keep controllers slim, to make them more reusable. So, I have separate controllers for each of the CRUD methods, which means I need a separate call for opening the database for each request, like so:
websiteService.openDatabase().then(function() {
websiteService.addWebsite($scope.website.url, $scope.website.color).then(function() {
}, function(err) {
console.log(err);
});
});
So, everytime I want to addWebsite
, I first openDatabase
and wait for promise to resolve.
websiteService
is a factory where all methods for working with IndexedDB are
What is the best practice here? If there's another way, not mentioned here, please do mention it.
If it helps, here's the complete controller code:
app.controller('AddWebsiteCtrl', ['$scope', '$location', '$routeParams', 'websiteService', function($scope, $location, $routeParams, websiteService) {
$scope.save = function() {
websiteService.openDatabase().then(function() {
websiteService.addWebsite($scope.website.url, $scope.website.color).then(function() {
}, function(err) {
console.log(err);
});
});
$location.path('/overview');
};
$scope.cancel = function() {
$location.path('/overview');
};
}]);
Upvotes: 3
Views: 714
Reputation: 18690
This question is unfortunately controversial. I personally recommend opening the database each time. Others will disagree (and have, prolifically).
If you can guarantee your database requests will always occur after a connection is established, it would be ok to use a single connection. If you are unsure of how indexedDB works in various browsers, or cannot guarantee the connection has been established yet, or cannot guarantee the connection is still open, then open a connection for each separate task.
If you know how async code works in general, you are probably fine doing whatever you find best, as neither way is technically wrong.
Upvotes: 5