UNPKG

@shopify/graphql-client

Version:

Shopify GraphQL Client - A lightweight generic GraphQL JS client to interact with Shopify GraphQL APIs

65 lines (61 loc) 2.47 kB
'use strict'; var constants = require('./constants.js'); var utilities = require('./utilities.js'); function generateHttpFetch({ clientLogger, customFetchApi = fetch, client = constants.CLIENT, defaultRetryWaitTime = constants.RETRY_WAIT_TIME, retriableCodes = constants.RETRIABLE_STATUS_CODES, }) { const httpFetch = async (requestParams, count, maxRetries) => { const nextCount = count + 1; const maxTries = maxRetries + 1; let response; try { response = await customFetchApi(...requestParams); clientLogger({ type: 'HTTP-Response', content: { requestParams, response, }, }); if (!response.ok && retriableCodes.includes(response.status) && nextCount <= maxTries) { throw new Error(); } const deprecationNotice = response?.headers.get('X-Shopify-API-Deprecated-Reason') || ''; if (deprecationNotice) { clientLogger({ type: 'HTTP-Response-GraphQL-Deprecation-Notice', content: { requestParams, deprecationNotice, }, }); } return response; } catch (error) { if (nextCount <= maxTries) { const retryAfter = response?.headers.get('Retry-After'); await sleep(retryAfter ? parseInt(retryAfter, 10) : defaultRetryWaitTime); clientLogger({ type: 'HTTP-Retry', content: { requestParams, lastResponse: response, retryAttempt: count, maxRetries, }, }); return httpFetch(requestParams, nextCount, maxRetries); } throw new Error(utilities.formatErrorMessage(`${maxRetries > 0 ? `Attempted maximum number of ${maxRetries} network retries. Last message - ` : ''}${utilities.getErrorMessage(error)}`, client)); } }; return httpFetch; } async function sleep(waitTime) { return new Promise((resolve) => setTimeout(resolve, waitTime)); } exports.generateHttpFetch = generateHttpFetch; //# sourceMappingURL=http-fetch.js.map