kevinohara80 / nforce

nforce is a node.js salesforce REST API wrapper for force.com, database.com, and salesforce.com
MIT License
474 stars 167 forks source link

Pass headers up for API Limit Throttling #105

Closed blak3r2 closed 6 years ago

blak3r2 commented 8 years ago

I don't want to use all of our customers salesforce API Requests. If I knew how close our customers were to hitting their limits, I could throttle my requests.

The salesforce api includes an header in the HTTP Response like: api-usage=27067/32000

With this one line change plugins could leverage this data and throttle requests. Here's a simple method I put together for extracting used / total. I think an even better solution would be to report back these numbers already decoded... but didn't want to rip up your codebase too much.

exports.getApiCallsUsed = function(body) {
    var obj = {};
    var usageString = _lo.get(body, "headers.sforce-limit-info");
    if(usageString) {
        try {
            usageString = usageString.split("=")[1];
            obj.used = usageString.split("/")[0];
            obj.total = usageString.split("/")[1];
            obj.remaining = obj.total - obj.used;
            obj.percentUsed = Math.round( (obj.used * 100) / obj.total);
            obj.percentRemaining = 100 - obj.percentUsed;
        }
        catch(err) {
            // do nothing wrong format
        }
    }
    return obj;
};
kevinohara80 commented 8 years ago

I like this idea but I want to make sure we do this the right way. In most callback implementations, this would be achieved by calling back with two arguments.

Example:

lib.myRequest(function(err, res, headers) {  });

...but the promises api needs to resolve to a single value. In which case your implementation would work.

lib.myRequest().then(function(res) { console.log(res.headers); });

I don't like tacking things on to the body of the response but it may be the best way. I'll ponder this a bit and try some things out.

blak3r2 commented 8 years ago

Great. Thanks for the consideration.

blak3r2 commented 8 years ago

Just curious if you thought about this any further.