Skip to content

Instantly share code, notes, and snippets.

@yocontra
Forked from AntonNguyen/gist:5349783
Last active December 16, 2015 01:59
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 yocontra/5359196 to your computer and use it in GitHub Desktop.
Save yocontra/5359196 to your computer and use it in GitHub Desktop.

I'm writing an app that talks to Apple to verifyReceipts. They have both a sandbox and production url that you can post to.

When communicating with Apple, if you receive a 21007 status, it means you were posting to the production url, when you should be posting to the sandbox one.

So I wrote some code to facilitate the retry logic. Here's a simplified version of my code:

var request = require('request')
  , Q = require('q')
  ;

var postToService = function(data, url) {
  var deferred = Q.defer();
  var options = {
    data: data,
    url: url
  };

  request.post(options, function(err, response, body) {
    if (err) return deferred.reject(err);
    if (hasErrors(response)) return deferred.reject(response);
    deferred.resolve(body);
  });

  return deferred.promise;
};

exports.verify = function(data) {
  var deferred = Q.defer();

  postToService(data, "https://production-url.com")
    .then(deferred.resolve)
    .fail(function(err) {
      if (err.code !== 21007) return deferred.reject(err);
      
      postToService(data, "https://sandbox-url.com")
        .then(deferred.resolve)
        .fail(deferred.reject);
    });

  return deferred.promise;
};

The retry portion in the verify function is pretty ugly and difficult to read with the nested promises. Is there a better way of doing this?

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