UNPKG

@unito/integration-sdk

Version:

Integration SDK

65 lines (57 loc) 2.6 kB
import * as HttpErrors from './httpErrors.js'; export class InvalidHandler extends Error {} /** * Parses a Retry-After header into a non-negative integer number of seconds to wait. Handles both the * delay-seconds and HTTP-date forms defined by RFC 9110, and rounds up so callers never retry earlier than * the provider asked. Returns undefined when the header is absent, blank, or unparseable. * * Internal to the SDK (errors.ts is not re-exported from index): the SDK populates HttpError.retryAfter * centrally in Provider.handleError, so integrations don't need to call this themselves. */ export function parseRetryAfterSeconds(headerValue: string | null | undefined): number | undefined { const trimmed = headerValue?.trim(); if (!trimmed) { return undefined; } const asSeconds = Number(trimmed); if (!Number.isNaN(asSeconds)) { return Math.max(0, Math.ceil(asSeconds)); } const asDate = new Date(trimmed).valueOf(); if (!Number.isNaN(asDate)) { return Math.max(0, Math.ceil((asDate - Date.now()) / 1000)); } return undefined; } /** * Processes provider response codes and returns the corresponding errors to be translated further in our responses * * @param responseStatus the reponseStatus of the request. Any HTTP response code passed here will result in an error! * @param message The message returned by the provider */ // Keep in errors.ts instead of httpErrors.ts because we do not need to export it outside of the sdk export function buildHttpError(responseStatus: number, message: string): HttpErrors.HttpError { let httpError: HttpErrors.HttpError; if (responseStatus === 400) { httpError = new HttpErrors.BadRequestError(message); } else if (responseStatus === 401) { httpError = new HttpErrors.UnauthorizedError(message); } else if (responseStatus === 403) { httpError = new HttpErrors.ForbiddenError(message); } else if (responseStatus === 404) { httpError = new HttpErrors.NotFoundError(message); } else if (responseStatus === 408) { httpError = new HttpErrors.TimeoutError(message); } else if (responseStatus === 410) { httpError = new HttpErrors.ResourceGoneError(message); } else if (responseStatus === 422) { httpError = new HttpErrors.UnprocessableEntityError(message); } else if (responseStatus === 423) { httpError = new HttpErrors.ProviderInstanceLockedError(message); } else if (responseStatus === 429) { httpError = new HttpErrors.RateLimitExceededError(message); } else { httpError = new HttpErrors.HttpError(message, responseStatus); } return httpError; }