Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add headers and status code with rejection + wait and retry once when limit is reached #364

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 29 additions & 6 deletions src/jira.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,45 @@ import url from 'url';
// eslint-disable-next-line no-underscore-dangle
const _request = require('postman-request');

function request(uri, options) {
async function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}

function request(uri, options, retry = true) {
return new Promise((resolve, reject) => {
_request(uri, options, (err, httpResponse) => {
_request(uri, options, async (err, httpResponse) => {
if (err) {
reject(err);
} else {
if (httpResponse.statusCode >= 400) {
reject(httpResponse.body);
} else if (httpResponse.statusCode >= 400) {
if (
(httpResponse.headers['retry-after'] || httpResponse.statusCode === 429)
&& retry
) {
await wait(parseInt(httpResponse.headers['retry-after'], 10) * 1000);
try {
const result = await request(uri, options, false);
resolve(result);
} catch (retryError) {
reject(retryError);
}
} else {
// eslint-disable-next-line prefer-promise-reject-errors
reject({
body: httpResponse.body,
headers: httpResponse.headers,
statusCode: httpResponse.statusCode,
});
}

} else {
// for compatibility with request-promise
resolve(httpResponse.body);
}
});
});
}

/**
* @name JiraApi
* @class
Expand Down