From a7370a780853cb494d9c1ab17cfe4ecc2f5611cc Mon Sep 17 00:00:00 2001 From: Michael Leanos Date: Sun, 10 Jul 2016 17:55:29 -0700 Subject: [PATCH] feat(articles): ArticlesService extended $resource (#1266) Extends the ArticlesService $resource object to include a custom method for creating, or updating, an Article instance. Related #1260 --- .../controllers/articles.client.controller.js | 10 +++--- .../services/articles.client.service.js | 36 ++++++++++++++++++- 2 files changed, 39 insertions(+), 7 deletions(-) diff --git a/modules/articles/client/controllers/articles.client.controller.js b/modules/articles/client/controllers/articles.client.controller.js index 2ee3cd1cdf..5fdc5cf472 100644 --- a/modules/articles/client/controllers/articles.client.controller.js +++ b/modules/articles/client/controllers/articles.client.controller.js @@ -31,12 +31,10 @@ return false; } - // TODO: move create/update logic to service - if (vm.article._id) { - vm.article.$update(successCallback, errorCallback); - } else { - vm.article.$save(successCallback, errorCallback); - } + // Create a new article, or update the current instance + vm.article.createOrUpdate() + .then(successCallback) + .catch(errorCallback); function successCallback(res) { $state.go('articles.view', { diff --git a/modules/articles/client/services/articles.client.service.js b/modules/articles/client/services/articles.client.service.js index 3dc4c7f534..e10e00fa3d 100644 --- a/modules/articles/client/services/articles.client.service.js +++ b/modules/articles/client/services/articles.client.service.js @@ -8,12 +8,46 @@ ArticlesService.$inject = ['$resource']; function ArticlesService($resource) { - return $resource('api/articles/:articleId', { + var Article = $resource('api/articles/:articleId', { articleId: '@_id' }, { update: { method: 'PUT' } }); + + angular.extend(Article.prototype, { + createOrUpdate: function () { + var article = this; + return createOrUpdate(article); + } + }); + + return Article; + + function createOrUpdate(article) { + if (article._id) { + return article.$update(onSuccess, onError); + } else { + return article.$save(onSuccess, onError); + } + + // Handle successful response + function onSuccess(article) { + // Any required internal processing from inside the service, goes here. + } + + // Handle error response + function onError(errorResponse) { + var error = errorResponse.data; + // Handle error internally + handleError(error); + } + } + + function handleError(error) { + // Log error + console.log(error); + } } }());