I have a service which needs to store some settings data in a DB and at the same time maintain a reference to that in the user'slocalStorage
(we want two users logged in to the same account to be able to view them differently). This method looks for an existing previewSession
in the localStorage
and if not found, creates one and generates a unique URL.
As you can see at the beginning, I'm using the $q
service to return a promise and then resolving that promise as and when all operations have finished. There is one use of the $http
service and the save call is on a $resource
object.
Is this a proper way to handle such a use-case, or could I have done it better?
To summarize the requirements:
- Method gets called with a settings parameter
- Method must always return a URL (unless an error occurs on the db level or some such thing)
var PREVIEW_SESSION_KEY_BASE = '<a constant string>';
function getPreviewSessionUrl(settings) {
var deferred = $q.defer();
$http.get('/' + appCode + '/reservedDomain',
function(appResponse) {
$localForage
.getItem(PREVIEW_SESSION_KEY_BASE + themeId)
.then(function(data) {
if (data) {
deferred.resolve(appResponse + '?<a query key>=' + data);
} else {
previewSessionResource.save(
{},
{
settings: settings
},
function(previewResponse) {
$localForage
.setItem(PREVIEW_SESSION_KEY_BASE + themeId, previewResponse)
.then(function(data) {
deferred.resolve(appResponse + '?<a query key>=' + data);
});
},
function(error) {
deferred.reject(error);
}
);
}
});
},
function(error) {
deferred.reject(error);
}
);
return deferred.promise;
}
then
calls. Thank you! \$\endgroup\$