Skip to content

Commit

Permalink
Relocate depleted event handler (#49)
Browse files Browse the repository at this point in the history
  • Loading branch information
jcpmmx authored Oct 11, 2021
1 parent 05fdad3 commit 0c4cb45
Showing 1 changed file with 17 additions and 11 deletions.
28 changes: 17 additions & 11 deletions lib/Methods.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,15 @@ const wait = (ms) => {
});
};

// On reservoir depletion, we wait 10000ms and reset the rate again (20 req/second limitation)
limiter.on('depleted', (empty) => {
if (!empty) {
wait(constants.LIMITER_WAIT_UPON_DEPLETION).then(() => {
reassignRate(constants.LIMITER_RESERVOIR);
});
}
});

/**
* The Method Factory
* @desc configures the actual method for each CRUD operations
Expand Down Expand Up @@ -108,15 +117,9 @@ const Methods = (key, api, ...args) => {
headers: api.api.headers,
timeout: timeoutInMilliseconds,
body: hasBody ? JSON.stringify(body) : undefined,
}).then((res) => {
// On reservoir depletion, we wait 10000ms and reset the rate again (20 req/second limitation)
limiter.on('depleted', (empty) => {
if (!empty) {
wait(constants.LIMITER_WAIT_UPON_DEPLETION).then(() => {
reassignRate(constants.LIMITER_RESERVOIR);
});
}
});
}))
.then((res) => {

// For every request, we compare the reservoir with the remainding rate limit in the header
limiter.currentReservoir()
.then((reservoir) => {
Expand All @@ -129,6 +132,7 @@ const Methods = (key, api, ...args) => {
// Return status code for deletion as the API does, else, return the body of the response
return operations === 'DELETE' ? res.status : res.json();
}

return res.json().then((error) => {
// Throws custom error according to errorCode
const errorCode = error.message.error;
Expand All @@ -150,9 +154,11 @@ const Methods = (key, api, ...args) => {
// All others, throw general HTTP error
throw new HttpError(errorInfo[0], errorInfo[1], errorInfo[2], errorInfo[3]);
});
}).catch((error) => {

})
.catch((error) => {
throw (error);
}));
});
};

module.exports = Methods;

0 comments on commit 0c4cb45

Please sign in to comment.