Skip to content

Instantly share code, notes, and snippets.

@ThomasBurleson
Last active August 8, 2018 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ThomasBurleson/9c5f521ca5acb37f6ded92a59534e6d2 to your computer and use it in GitHub Desktop.
Save ThomasBurleson/9c5f521ca5acb37f6ded92a59534e6d2 to your computer and use it in GitHub Desktop.
Demonstration of classic REST service anti-pattern

Typical coding example for a sequence of asynchronous REST calls:

function update(ev, updateDiff) {
  // get current event from Back End
  return scheduleService.getEvent(ev.id).then(function(event) {
    // send updates to Back end
    return scheduleService.editEvent(ev.id, event.version, updateDiff).then(function(evt) {
      var pack = findAircraftPackById(evt.aircraft.id);
      // get whole aircraft schedules in order to get repo legs updated
      return fetchAircraft(pack).then(function(resp) {
        return resp;
      }, function(error) {
        return $q.reject(error);
      });
    }, function(error) {
      return $q.reject(error);
    });
  }, function(error) {
    return $q.reject(error);
  });
}

This is not maintainable, not DRY!!

@ThomasBurleson
Copy link
Author

ThomasBurleson commented Nov 12, 2017

Refactoring nesting-hell ^ using imperative, declarative techniques:

function update(ev, updateDiff) {
    const announceError = (error) => $q.reject(error);
    const loadEvent     = (id) => scheduleService.getEvent(id);
    const editEvent     = (event) => scheduleService.editEvent(ev.id, event.version, updateDiff);
    const loadAircraft  = (aircraft) => fetchAircraft(aircraft.id);

    
    return loadEvent(ev.id)
            .then ( editEvent     )
            .then ( loadAircraft )
            .catch( announceError );

}

@ThomasBurleson
Copy link
Author

This refactoring above is wrong.

  • Do you see why?
  • How would you fix it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment