UNPKG

@shopify/shopify-api

Version:

Shopify API Library for Node - accelerate development with support for authentication, graphql proxy, webhooks

1 lines 10.3 kB
{"version":3,"file":"common.mjs","sources":["../../../../../../lib/clients/common.ts"],"sourcesContent":["import {\n HTTPResponseLog,\n HTTPRetryLog,\n HTTPResponseGraphQLDeprecationNotice,\n LogContent,\n} from '@shopify/admin-api-client';\n\nimport * as ShopifyErrors from '../error';\nimport {LIBRARY_NAME, StatusCode} from '../types';\nimport {ConfigInterface} from '../base-types';\nimport {SHOPIFY_API_LIBRARY_VERSION} from '../version';\nimport {\n abstractRuntimeString,\n canonicalizeHeaders,\n getHeader,\n} from '../../runtime';\nimport {logger} from '../logger';\n\nexport function getUserAgent(config: ConfigInterface): string {\n let userAgentPrefix = `${LIBRARY_NAME} v${SHOPIFY_API_LIBRARY_VERSION} | ${abstractRuntimeString()}`;\n if (config.userAgentPrefix) {\n userAgentPrefix = `${config.userAgentPrefix} | ${userAgentPrefix}`;\n }\n\n return userAgentPrefix;\n}\n\nfunction serializeResponse(response: Response | any) {\n if (!response) {\n return {error: 'No response object provided'};\n }\n\n try {\n const {status, statusText, ok, redirected, type, url, headers} = response;\n\n const serialized: any = {\n status,\n statusText,\n ok,\n redirected,\n type,\n url,\n };\n\n if (headers?.entries) {\n serialized.headers = Object.fromEntries(headers.entries());\n } else if (headers) {\n serialized.headers = headers;\n }\n\n return serialized;\n } catch {\n return response;\n }\n}\n\nexport function clientLoggerFactory(config: ConfigInterface) {\n return (logContent: LogContent) => {\n if (config.logger.httpRequests) {\n switch (logContent.type) {\n case 'HTTP-Response': {\n const responseLog: HTTPResponseLog['content'] = logContent.content;\n logger(config).debug('Received response for HTTP request', {\n requestParams: JSON.stringify(responseLog.requestParams),\n response: JSON.stringify(serializeResponse(responseLog.response)),\n });\n break;\n }\n case 'HTTP-Retry': {\n const responseLog: HTTPRetryLog['content'] = logContent.content;\n logger(config).debug('Retrying HTTP request', {\n requestParams: JSON.stringify(responseLog.requestParams),\n retryAttempt: responseLog.retryAttempt,\n maxRetries: responseLog.maxRetries,\n response: responseLog.lastResponse\n ? JSON.stringify(serializeResponse(responseLog.lastResponse))\n : 'undefined',\n });\n break;\n }\n case 'HTTP-Response-GraphQL-Deprecation-Notice': {\n const responseLog: HTTPResponseGraphQLDeprecationNotice['content'] =\n logContent.content;\n logger(config).debug(\n 'Received response containing Deprecated GraphQL Notice',\n {\n requestParams: JSON.stringify(responseLog.requestParams),\n deprecationNotice: responseLog.deprecationNotice,\n },\n );\n break;\n }\n default: {\n logger(config).debug(`HTTP request event: ${logContent.content}`);\n break;\n }\n }\n }\n };\n}\n\nexport function throwFailedRequest(\n body: any,\n atMaxRetries: boolean,\n response?: Response,\n): never {\n if (typeof response === 'undefined') {\n const message = body?.errors?.message ?? '';\n throw new ShopifyErrors.HttpRequestError(\n `Http request error, no response available: ${message}`,\n );\n }\n\n const responseHeaders = canonicalizeHeaders(\n Object.fromEntries(response.headers.entries() ?? []),\n );\n\n if (response.status === StatusCode.Ok && body.errors.graphQLErrors) {\n throw new ShopifyErrors.GraphqlQueryError({\n message:\n body.errors.graphQLErrors?.[0].message ?? 'GraphQL operation failed',\n response: response as Record<string, any>,\n headers: responseHeaders,\n body: body as Record<string, any>,\n });\n }\n\n const errorMessages: string[] = [];\n if (body.errors) {\n errorMessages.push(JSON.stringify(body.errors, null, 2));\n }\n const xRequestId = getHeader(responseHeaders, 'x-request-id');\n if (xRequestId) {\n errorMessages.push(\n `If you report this error, please include this id: ${xRequestId}`,\n );\n }\n\n const errorMessage = errorMessages.length\n ? `:\\n${errorMessages.join('\\n')}`\n : '';\n const code = response.status;\n const statusText = response.statusText;\n\n switch (true) {\n case response.status === StatusCode.TooManyRequests: {\n if (atMaxRetries) {\n throw new ShopifyErrors.HttpMaxRetriesError(\n 'Attempted the maximum number of retries for HTTP request.',\n );\n } else {\n const retryAfter = getHeader(responseHeaders, 'Retry-After');\n throw new ShopifyErrors.HttpThrottlingError({\n message: `Shopify is throttling requests ${errorMessage}`,\n code,\n statusText,\n body,\n headers: responseHeaders,\n retryAfter: retryAfter ? parseFloat(retryAfter) : undefined,\n });\n }\n }\n case response.status >= StatusCode.InternalServerError:\n if (atMaxRetries) {\n throw new ShopifyErrors.HttpMaxRetriesError(\n 'Attempted the maximum number of retries for HTTP request.',\n );\n } else {\n throw new ShopifyErrors.HttpInternalError({\n message: `Shopify internal error${errorMessage}`,\n code,\n statusText,\n body,\n headers: responseHeaders,\n });\n }\n default:\n throw new ShopifyErrors.HttpResponseError({\n message: `Received an error response (${response.status} ${response.statusText}) from Shopify${errorMessage}`,\n code,\n statusText,\n body,\n headers: responseHeaders,\n });\n }\n}\n"],"names":["ShopifyErrors.HttpRequestError","ShopifyErrors.GraphqlQueryError","ShopifyErrors.HttpMaxRetriesError","ShopifyErrors.HttpThrottlingError","ShopifyErrors.HttpInternalError","ShopifyErrors.HttpResponseError"],"mappings":";;;;;;;AAkBM,SAAU,YAAY,CAAC,MAAuB,EAAA;IAClD,IAAI,eAAe,GAAG,CAAA,EAAG,YAAY,CAAA,EAAA,EAAK,2BAA2B,CAAA,GAAA,EAAM,qBAAqB,EAAE,CAAA,CAAE;AACpG,IAAA,IAAI,MAAM,CAAC,eAAe,EAAE;QAC1B,eAAe,GAAG,GAAG,MAAM,CAAC,eAAe,CAAA,GAAA,EAAM,eAAe,EAAE;IACpE;AAEA,IAAA,OAAO,eAAe;AACxB;AAEA,SAAS,iBAAiB,CAAC,QAAwB,EAAA;IACjD,IAAI,CAAC,QAAQ,EAAE;AACb,QAAA,OAAO,EAAC,KAAK,EAAE,6BAA6B,EAAC;IAC/C;AAEA,IAAA,IAAI;AACF,QAAA,MAAM,EAAC,MAAM,EAAE,UAAU,EAAE,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,GAAG,EAAE,OAAO,EAAC,GAAG,QAAQ;AAEzE,QAAA,MAAM,UAAU,GAAQ;YACtB,MAAM;YACN,UAAU;YACV,EAAE;YACF,UAAU;YACV,IAAI;YACJ,GAAG;SACJ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