Skip to main content

http.ts

Source: sdks/typescript/packages/sdk/src/http.ts. Back to the TypeScript SDK reference index.

note

This page is generated by tools/docs/gen_sdk_reference.py from the SDK sources and the OpenAPI text folders. Do not edit it by hand: change the source and regenerate.

Type alias FetchLike​

Signature of a fetch function: URL and init in, Response out.

Definition: (input: string, init?: RequestInit) => Promise<Response>.

Type alias HttpMethod​

GET, POST, PUT, PATCH or DELETE.

Definition: "GET" \| "POST" \| "PUT" \| "PATCH" \| "DELETE".

Type alias QueryValue​

Value of a query parameter; null and undefined are left out and an array repeats the parameter.

Definition: string \| number \| boolean \| null \| undefined \| string[].

Interface ClientOptions​

Options of the HTTP client: base URL, credentials, dev mode headers, retries, timeout and fetch.

Fields:

NameTypeRequiredDescription
baseUrlstringyesControl Plane base URL, for example <control-plane-url> (without /v1).
apiKeystringnoTenant API key, sent as X-API-Key.
tokenstring | (() => string | Promise<string>)noOIDC bearer token (string or async provider for refresh).
tenantstringnoDev mode tenant slug, sent as X-Dev-Tenant (only honored when the server runs with EAI_AUTH_DEV=1).
devUserstringnoDev mode user id, sent as X-Dev-User.
devRolesstring[]noDev mode roles, sent as X-Dev-Roles.
projectstringnoIdentifier of the project the results are restricted to.
environment"dev" | "test" | "staging" | "prod" | (string & {})noEnvironment (dev, test, staging, prod or another name), sent as X-Environment.
localeLocalenoLanguage of the messages, en (default) or fr, also sent as Accept-Language.
fetchFetchLikenofetch implementation to use; defaults to the global fetch.
retriesnumbernoNumber of retries on 429, 5xx and network errors (default 2).
retryBaseDelayMsnumbernoBase delay of the exponential backoff in ms (default 300).
retryMaxDelayMsnumbernoMaximum delay between retries in ms (default 20000).
timeoutMsnumbernoPer request timeout in ms (default 60000, 0 disables).
headersRecord<stringnoExtra headers sent with every request.
sleep(ms: number) => Promise<void>noSleep function used between retries (injectable for tests).

Interface RequestOptions​

Options of one request: path parameters, query, body, headers, idempotency key, trace, signal and response type.

Fields:

NameTypeRequiredDescription
paramsRecord<stringnoValues of the {name} placeholders of the route.
queryRecord<stringnoQuery string parameters; undefined and null values are left out, arrays repeat the parameter.
bodyunknownnoBody of the request: sent as JSON, or as is for FormData, Blob, ArrayBuffer and URLSearchParams.
headersRecord<stringnoHeaders of the event, string values. The trace context is added.
idempotencyKeystringnoIdempotency-Key of a POST; a random one is generated when missing.
traceparentstringnoW3C traceparent header to send; a new one is generated when missing.
signalAbortSignalnoAbortSignal that cancels the request.
responseType"json" | "text" | "binary" | "stream"noResponse handling: json (default), text, binary, stream (raw Response).
noRetrybooleannoDisable retries for this call.

Interface ApiResponse​

Decoded body of a response with its HTTP status, headers and request id.

Fields:

NameTypeRequiredDescription
dataTyesDecoded body of the response.
statusnumberyesHTTP status of the response.
headersHeadersyesHeaders of the event, string values. The trace context is added.
requestIdstring | undefinedyesValue of the x-request-id response header.

Class HttpClient​

HTTP transport of the SDK: builds the URL and headers, retries 429, 5xx and network errors, and maps errors to typed classes.

Attributes:

NameTypeRequiredDescription
baseUrlstringyesBase URL without its trailing slashes.
localeLocaleyesLanguage of the messages and of Accept-Language.

Constructor HttpClient​

new HttpClient(opts: ClientOptions)

Checks the base URL and the fetch implementation; throws missing_base_url, no_fetch or TypeError on a bad URL.

NameTypeDefaultRequiredDescription
optsClientOptionsyesPer call options (query, idempotency key, traceparent, headers).

HttpClient.headers​

async headers(method: HttpMethod, o: RequestOptions): Promise<Record<string, string>>

Builds the headers of a request: Accept, Accept-Language, traceparent, credentials, dev mode, project, environment and Idempotency-Key on POST.

NameTypeDefaultRequiredDescription
methodHttpMethodyesHTTP method; a POST gets an Idempotency-Key.
oRequestOptionsyesPer call options (idempotency key, traceparent, headers).

Returns: Promise<Record<string, string>>. The headers, those of the request options last.

HttpClient.raw​

async raw(method: HttpMethod, template: string, o: RequestOptions = {}): Promise<ApiResponse<T>>

Performs a request and returns the decoded body with status and headers.

NameTypeDefaultRequiredDescription
methodHttpMethodyesHTTP method of the request.
templatestringyesRoute relative to the base URL, with {name} placeholders filled from params.
oRequestOptions{}noPer call options (idempotency key, traceparent, headers).

Returns: Promise<ApiResponse<T>>. Body, status, headers and request id; throws the typed EaiError on an error status.

Raises: EaiError.

HttpClient.request​

async request(method: HttpMethod, template: string, o: RequestOptions = {}): Promise<T>

Performs a request and returns only the decoded body.

NameTypeDefaultRequiredDescription
methodHttpMethodyesHTTP method of the request.
templatestringyesRoute relative to the base URL, with {name} placeholders filled from params.
oRequestOptions{}noPer call options (idempotency key, traceparent, headers).

Returns: Promise<T>. Decoded body of the response.

HttpClient.toJSON​

toJSON(): Record<string, unknown>

Never exposes the API key or token (console.log, JSON.stringify, util.inspect).

This element takes no parameter.

Returns: Record<string, unknown>. Base URL, locale and the masked API key and token.

HttpClient.transfer​

async transfer(url: string, init: RequestInit): Promise<Response>

Transfer to or from a presigned storage URL: the configured fetch, without any platform credential.

NameTypeDefaultRequiredDescription
urlstringyesPresigned storage URL.
initRequestInityesfetch options of the transfer (method, body, headers); redirects are not followed.

Returns: Promise<Response>. The response; a status of 300 or more throws storage_transfer_failed.

Raises: EaiError.

HttpClient.url​

url(template: string, params?: Record<string, string | number>, query?: Record<string, QueryValue>): string

Builds the full URL of a route.

NameTypeDefaultRequiredDescription
templatestringyesRoute relative to the base URL, with {name} placeholders.
paramsRecord<string, string | number>noExtra fields merged into the request.
queryRecord<string, QueryValue>noQuery string parameters of the route.

Returns: string. Base URL, filled path and query string.

Functions​

isLocalHost​

isLocalHost(host: string): boolean

True for localhost, 127.0.0.1 and ::1.

NameTypeDefaultRequiredDescription
hoststringyesHost name to check, case insensitive.

Returns: boolean. True for a local host.

validateBaseUrl​

validateBaseUrl(raw: string): URL

Throws unless the URL is https, or http on a local host, without embedded credentials.

NameTypeDefaultRequiredDescription
rawstringyesReturn an ApiResponse (data, status, headers) instead of the decoded body.

Returns: URL. The parsed URL; throws TypeError otherwise.

Raises: TypeError.

validateWsUrl​

validateWsUrl(raw: string): string

Throws unless the URL is wss, or ws on a local host.

NameTypeDefaultRequiredDescription
rawstringyesReturn an ApiResponse (data, status, headers) instead of the decoded body.

Returns: string. The URL unchanged; throws TypeError otherwise.

Raises: TypeError.

generateTraceparent​

generateTraceparent(): string

W3C trace context header value: version 00, random trace id and parent id, sampled.

This element takes no parameter.

Returns: string. A header value of the form 00-<trace id>-<parent id>-01.

generateId​

generateId(): string

RFC 4122 version 4 identifier, used for Idempotency-Key.

This element takes no parameter.

Returns: string. A random UUID string.

parseRetryAfter​

parseRetryAfter(value: string | null, now = Date.now()): number | undefined

Parses Retry-After (seconds or HTTP date) into milliseconds.

NameTypeDefaultRequiredDescription
valuestring | nullyesValue of the Retry-After header.
nowDate.now()noCurrent time in milliseconds, used for an HTTP date (default Date.now()).

Returns: number \| undefined. Delay in milliseconds, at least 0, or undefined when the value is missing or unreadable.

fillPath​

fillPath(template: string, params: Record<string, string | number> = {}): string

Fills {name} placeholders. The {path} placeholder keeps its slashes.

NameTypeDefaultRequiredDescription
templatestringyesRoute with {name} placeholders; a missing value throws TypeError.
paramsRecord<string, string | number>{}noExtra fields merged into the request.

Returns: string. The route with the values URL encoded.

Raises: TypeError.

buildQuery​

buildQuery(query: Record<string, QueryValue> = {}): string

Builds a query string from a map, leaving out null and undefined and repeating array values.

NameTypeDefaultRequiredDescription
queryRecord<string, QueryValue>{}noQuery string parameters of the route.

Returns: string. The query string starting with ?, or an empty string.