I built a function in my NodeJS backend which has that purpose to retry for 10 times a request if a value on first request is equal to null. This behavior is need it because there is a worker function which uploads PDF to AWS, so the value I'm retrieving by the new function contains a PDF URL which very often on first request is null.
The goal is to check at first if we have the pdfUrl if that is not NULL so return the data.
If the pdfURLfor some reason is NULL then the function need to retry the request with a timeout of 20s and max 10 retries.
The function I tried is as follow and have several issues:
async function getIcfDocument(documentId, { log }) {
log.info('Getting IcfDocument with last revision pdfUrl');
const MAX_RETRIES = 10;
const timeout = 20000;
let data;
for (let i = 0; i <= MAX_RETRIES; i += 1) {
try {
const { icfDocuments } = await request(
CONSENT_SERVICE_URL,
getICFDocumentRecipientsQuery,
{
documentId,
}
);
if (icfDocuments.nodes[0].revision.pdfUrl) {
log.info('Success the revision pdfUrl is present');
data = icfDocuments;
} else {
log.debug(
'Waiting to retrieve the last revision pdfUrl %s ms',
timeout
);
await sleep(timeout);
log.debug('Retrying times %s', i);
}
} catch (err) {
log.error(
'Failed to retrieve the data for document %s, Error: %s',
documentId,
err.message
);
return null;
}
}
return data;
}
Will be nice to see a better way to what I have tried as I have some difficulties to make it so.
The request method above is requesting to a GQL query that why was implemented in this way
const { icfDocuments } = await request(
CONSENT_SERVICE_URL,
getICFDocumentRecipientsQuery,
{
documentId,
}
);
The icfDocuments is the resulting OBJ of the query which contains the urlPdfand other information. This query has to be retried if that url is null for max 10 times and 20s timeout between requests.
The query is this one as info
const getICFDocumentRecipientsQuery = gql`
query GetICFDocumentRecipients($documentId: ID!) {
icfDocuments(filter: { ids: [$documentId] }, pagination: { limit: 1 }) {
nodes {
id
recipients {
id
email
phone
locale
}
revision {
pdfUrl
}
}
}
}
`;
async function getIcfDocument(documentId, { log }) {
log.info('Getting IcfDocument with last revision pdfUrl');
const MAX_RETRIES = 10;
const timeout = 20000;
for (let i = 0; i <= MAX_RETRIES; i++) {
try {
const { icfDocuments } = await request(
CONSENT_SERVICE_URL,
getICFDocumentRecipientsQuery,
{
documentId,
}
);
if (icfDocuments.nodes[0].revision.pdfUrl) {
log.info('Success the revision pdfUrl is present');
return data; // SOLUTION TO #1
} else {
if (i == MAX_RETRIES) return log.error('Failed to retrieve pdfUrl after %s tries.', MAX_RETRIES); // SOLUTION TO #2
log.debug(
'Waiting to retrieve the last revision pdfUrl %s ms',
timeout
);
await sleep(timeout);
log.debug('Retrying times %s', i);
}
} catch (err) {
log.error(
'Failed to retrieve the data for document %s, Error: %s',
documentId,
err.message
);
break;
}
}
return null;
}