angularjs-in-action / angello

MIT License
247 stars 136 forks source link

Use of $http improvements #23

Open ThomasBurleson opened 10 years ago

ThomasBurleson commented 10 years ago

Your do not need to wrap $http() calls with $q.defer() usages.

var find = function () {
            var deferred = $q.defer();
            var url = ENDPOINT_URI + 'clients/' + AuthService.getCurrentUserId() + '/stories.json';

            $http.get(url).success(deferred.resolve).error(deferred.reject);

            return deferred.promise;
        };

And consolidate all URLs into a url map. Consider this result:

var URLS = {
      STORY : {
          findAll           : "{0}/clients/{1}/stories.json"
        , loadStoryDetails  : "{0}/clients/{1}/stories/{2}.json"
      }
    };

function findAllStories( ) 
{
  return $http.get( supplant( 
    URLS.STORY.findAll, [ ENDPOINT_URI, AuthService.getCurrentUserId() ]
  ));
}

function loadStory( storyID ) 
{
  return $http.get( supplant( 
    URLS.STORY.loadStory, [ ENDPOINT_URI, AuthService.getCurrentUserId(), storyID ]
  ));
}
ThomasBurleson commented 10 years ago

If you externalize all dataservice endpoint/urls into a serviceURLs factory, you can inject this service map instead of injecting the flat ENDPOINT_URL constant. You could also configure your ENDPOINT_URL during config() time and update all urls in the serviceURLs instance before the service map is injected in other Services.

/**
 * URLS before prefixing with ENDPOINT
 *
 * var URLS = { * 
 *      STORY : {
 *          FIND_ALL    : "/clients/{1}/stories.json"
 *        , LOAD_STORY  : "/clients/{1}/stories/{2}.json"
 *      }
 *      USER : {
 *          LOAD_ALL : "clients/{0}/users.json"
 *      }
 *    };
 */

// Register the StoryService with AngularJS

myModule.factory(
    'storyService', 
    [ 'authService', 'serviceURLs', '$http', StoryService ]
);

function StoryService( authService, serviceURLs, $http ) 
{
  // Published `promise-returning` API
  return {
    findAllStories : findAllStories,
    loadStory      : loadStory
  }

  // **********************************
  // Internal Methods
  // **********************************

  function findAllStories( ) 
  {
    return $http.get( supplant( 
      serviceURLs.STORY.FIND_ALL, [ AuthService.getCurrentUserId() ]
    ));
  }

  function loadStory( storyID ) 
  {
    return $http.get(supplant( 
      serviceURLs.STORY.LOAD_STORY, [ AuthService.getCurrentUserId(), storyID ]
    ));
  }
}