UNPKG

@sp-api-sdk/common

Version:

Common library for the Amazon Selling Partner API (SP-API) SDK: Axios factory, regions, rate limiting and errors

157 lines (153 loc) 6.05 kB
import axios, { AxiosError, isAxiosError } from "axios"; import { errorLogger, requestLogger, responseLogger } from "axios-logger"; import axiosRetry from "axios-retry"; import { SellingPartnerApiAuthError } from "@sp-api-sdk/auth"; import { URL as URL$1 } from "node:url"; import { sync } from "read-pkg-up"; //#region src/regions.ts /** Endpoint mapping for each Selling Partner API region. */ const sellingPartnerRegions = { na: { endpoints: { production: "https://sellingpartnerapi-na.amazon.com", sandbox: "https://sandbox.sellingpartnerapi-na.amazon.com" } }, eu: { endpoints: { production: "https://sellingpartnerapi-eu.amazon.com", sandbox: "https://sandbox.sellingpartnerapi-eu.amazon.com" } }, fe: { endpoints: { production: "https://sellingpartnerapi-fe.amazon.com", sandbox: "https://sandbox.sellingpartnerapi-fe.amazon.com" } } }; //#endregion //#region src/errors.ts /** Error thrown when a Selling Partner API request fails. Wraps the underlying Axios error with a message that includes the API name, version, and HTTP status code (or "No response" for network errors). */ var SellingPartnerApiError = class extends AxiosError { /** The original error message from the failed HTTP request. */ innerMessage; /** The API name extracted from the request URL path (e.g. `"orders"`). */ apiName; /** The API version extracted from the request URL path (e.g. `"v0"`). */ apiVersion; constructor(error) { super("Unknown error", error.code, error.config, error.request, error.response); this.innerMessage = error.message; if (error.config.url) { const [apiName, apiVersion] = new URL$1(error.config.url).pathname.split("/").slice(1); const apiPrefix = `${apiName} (${apiVersion})`; this.apiName = apiName; this.apiVersion = apiVersion; this.message = error.response ? `${apiPrefix} error: Response code ${error.response.status}` : `${apiPrefix} error: No response`; } this.name = this.constructor.name; } }; const packageJson = sync()?.packageJson ?? { _id: "", readme: "", name: "@sp-api-sdk/common", version: "unknown" }; //#endregion //#region src/axios.ts /** Creates a pre-configured Axios instance for a Selling Partner API client. The instance handles authentication, rate-limit retries, error wrapping, and optional request/response logging. @param configuration - Client configuration options. @param rateLimits - Per-endpoint rate limits used for retry delay calculation. @returns An object containing the configured Axios instance and the resolved API endpoint. */ function createAxiosInstance({ auth, restrictedDataToken, region, userAgent = `${packageJson.name}/${packageJson.version}`, sandbox = false, rateLimiting, logging }, rateLimits) { if (!Object.hasOwn(sellingPartnerRegions, region)) throw new TypeError(`Unknown or unsupported region: ${region}`); const regionConfiguration = sellingPartnerRegions[region]; const instance = axios.create({ headers: { "user-agent": userAgent } }); const endpoint = regionConfiguration.endpoints[sandbox ? "sandbox" : "production"]; if (rateLimiting?.retry) axiosRetry(instance, { retryCondition: (error) => error.response?.status === 429, retryDelay(retryCount, error) { const url = new URL(error.config.url); const method = error.config.method?.toLowerCase(); const amznRateLimitHeader = error.response?.headers["x-amzn-ratelimit-limit"]; const amznRateLimit = amznRateLimitHeader ? Number(amznRateLimitHeader) : NaN; const rateLimit = Number.isNaN(amznRateLimit) ? rateLimits.find((rateLimit) => rateLimit.method.toLowerCase() === method && rateLimit.urlRegex.test(url.pathname))?.rate : amznRateLimit; const requestInterval = rateLimit !== void 0 && rateLimit > 0 ? 1e3 / rateLimit : void 0; const delay = requestInterval === void 0 ? 6e4 : requestInterval + 1500; if (rateLimiting.onRetry) rateLimiting.onRetry({ delay, rateLimit, retryCount, error }); return delay; } }); instance.interceptors.request.use(async (config) => { config.headers["x-amz-access-token"] = restrictedDataToken ?? await auth.getAccessToken(); return config; }); instance.interceptors.response.use(async (response) => response, async (error) => { if (isAxiosError(error) && !(error instanceof SellingPartnerApiAuthError)) throw new SellingPartnerApiError(error); throw error; }); if (logging?.request !== void 0) { const requestLoggerOptions = logging.request === true ? void 0 : logging.request; if (requestLoggerOptions?.headers) console.warn("WARNING: You have enabled logging of request headers, this can leak authentication information, you should disable in production."); instance.interceptors.request.use((config) => { return { ...requestLogger(config, { prefixText: `sp-api-sdk/${region}`, dateFormat: "isoDateTime", method: true, url: true, params: false, data: true, headers: false, logger: console.info, ...requestLoggerOptions }), headers: config.headers }; }); } if (logging?.response !== void 0) { const responseLoggerOptions = logging.response === true ? void 0 : logging.response; instance.interceptors.response.use((response) => responseLogger(response, { prefixText: `sp-api-sdk/${region}`, dateFormat: "isoDateTime", status: true, statusText: false, params: false, data: false, headers: true, logger: console.info, ...responseLoggerOptions })); } if (logging?.error !== void 0) { const errorLoggerOptions = logging.error === true ? void 0 : logging.error; instance.interceptors.response.use((response) => response, async (error) => errorLogger(error, { prefixText: `sp-api-sdk/${region}`, dateFormat: "isoDateTime", status: true, statusText: false, params: false, data: false, headers: true, logger: console.error, ...errorLoggerOptions })); } return { axios: instance, endpoint }; } //#endregion export { SellingPartnerApiError, createAxiosInstance, sellingPartnerRegions }; //# sourceMappingURL=index.js.map