Skip to content

HttpClientMixin

HttpClientMixin is a mixin function for building light-weight HTTP clients.

Classes

HttpError

Defined in: packages/js-utils/src/services/http-client-mixin/http-error.class.ts:4

Represents an error that occurred during an HTTP request triggered by the client.

Extends

  • Error

Constructors

Constructor

new HttpError(init): HttpError

Defined in: packages/js-utils/src/services/http-client-mixin/http-error.class.ts:14

Parameters
init

HttpError

Returns

HttpError

Overrides

Error.constructor

Properties

body?

optional body: string | object

Defined in: packages/js-utils/src/services/http-client-mixin/http-error.class.ts:12

The response body that came with the error.

cause?

optional cause: unknown

Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es2022.error.d.ts:26

Inherited from

Error.cause

message

message: string

Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es5.d.ts:1077

Inherited from

Error.message

name

name: string

Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es5.d.ts:1076

Inherited from

Error.name

stack?

optional stack: string

Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es5.d.ts:1078

Inherited from

Error.stack

status?

optional status: number

Defined in: packages/js-utils/src/services/http-client-mixin/http-error.class.ts:8

The status code of the response that caused the error.

stackTraceLimit

static stackTraceLimit: number

Defined in: node_modules/.pnpm/@types+node@22.15.19/node_modules/@types/node/globals.d.ts:161

The Error.stackTraceLimit property specifies the number of stack frames collected by a stack trace (whether generated by new Error().stack or Error.captureStackTrace(obj)).

The default value is 10 but may be set to any valid JavaScript number. Changes will affect any stack trace captured after the value has been changed.

If set to a non-number value, or set to a negative number, stack traces will not capture any frames.

Inherited from

Error.stackTraceLimit

Methods

captureStackTrace()

static captureStackTrace(targetObject, constructorOpt?): void

Defined in: node_modules/.pnpm/@types+node@22.15.19/node_modules/@types/node/globals.d.ts:145

Creates a .stack property on targetObject, which when accessed returns a string representing the location in the code at which Error.captureStackTrace() was called.

const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack; // Similar to `new Error().stack`

The first line of the trace will be prefixed with ${myObject.name}: ${myObject.message}.

The optional constructorOpt argument accepts a function. If given, all frames above constructorOpt, including constructorOpt, will be omitted from the generated stack trace.

The constructorOpt argument is useful for hiding implementation details of error generation from the user. For instance:

function a() {
b();
}
function b() {
c();
}
function c() {
// Create an error without stack trace to avoid calculating the stack trace twice.
const { stackTraceLimit } = Error;
Error.stackTraceLimit = 0;
const error = new Error();
Error.stackTraceLimit = stackTraceLimit;
// Capture the stack trace above function b
Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
throw error;
}
a();
Parameters
targetObject

object

constructorOpt?

Function

Returns

void

Inherited from

Error.captureStackTrace

prepareStackTrace()

static prepareStackTrace(err, stackTraces): any

Defined in: node_modules/.pnpm/@types+node@22.15.19/node_modules/@types/node/globals.d.ts:149

Parameters
err

Error

stackTraces

CallSite[]

Returns

any

See

https://v8.dev/docs/stack-trace-api#customizing-stack-traces

Inherited from

Error.prepareStackTrace

Interfaces

EndpointDefinition<TArgs, TFunction, TTransformedResult>

Defined in: packages/js-utils/src/services/http-client-mixin/types.ts:69

The definition of an endpoint to be used by the client.

Type Parameters

TArgs

TArgs extends EndpointFunctionArgs = never

TFunction

TFunction extends EndpointFunction<TArgs> = EndpointFunction<TArgs>

The type of the endpoint function.

TTransformedResult

TTransformedResult = any

The type of the transformed result.

Properties

errorHandlers?

optional errorHandlers: ErrorHandler[]

Defined in: packages/js-utils/src/services/http-client-mixin/types.ts:90

The set of error handlers for the endpoint. These local error handlers will be called before the global error handlers.

function

function: TFunction

Defined in: packages/js-utils/src/services/http-client-mixin/types.ts:77

The function that will be called when the endpoint is invoked.

transformer()?

optional transformer: (response) => TTransformedResult

Defined in: packages/js-utils/src/services/http-client-mixin/types.ts:85

A function that will be called to transform the response from the server. The transformer will be called implicitly after the original promise has resolved.

Parameters
response

Awaited<ReturnType<TFunction>>

The responsese from the server.

Returns

TTransformedResult

The transformed result.


EndpointParams<TArgs>

Defined in: packages/js-utils/src/services/http-client-mixin/types.ts:34

The set of parameters that are exposed when using an endpoint.

Type Parameters

TArgs

TArgs extends EndpointFunctionArgs = void

Properties

args

args: TArgs

Defined in: packages/js-utils/src/services/http-client-mixin/types.ts:38

The arguments to be passed to the endpoint function.


HttpClientOptions<TEndpoints>

Defined in: packages/js-utils/src/services/http-client-mixin/types.ts:101

The options to hand over to the client.

Type Parameters

TEndpoints

TEndpoints extends Endpoints

The set of registered Endpoints.

Properties

endpoints

endpoints: TEndpoints

Defined in: packages/js-utils/src/services/http-client-mixin/types.ts:105

The set of Endpoints to be used by the client.

globalErrorHandlers?

optional globalErrorHandlers: ErrorHandler[]

Defined in: packages/js-utils/src/services/http-client-mixin/types.ts:111

A set of global ErrorHandlers. These will be called for every error that occurs, regardless of the endpoint. These global error handlers will be called after any local error handlers.


HttpRequest<T>

Defined in: packages/js-utils/src/services/http-client-mixin/http-request.class.ts:9

An object containing information about an HTTP request that has been omitted via HttpClientMixin. Can be used to access the promised response, transformed result or to cancel the request.

Type Parameters

T

T extends EndpointDefinition = EndpointDefinition

Accessors

endpointDefinition
Get Signature

get endpointDefinition(): T

Defined in: packages/js-utils/src/services/http-client-mixin/http-request.class.ts:13

The EndpointDefinition that was used to create the request.

Returns

T

error
Get Signature

get error(): HttpError

Defined in: packages/js-utils/src/services/http-client-mixin/http-request.class.ts:31

The error the request has thrown. null in case the request hasn’t yet thrown an error or has succeeded.

Returns

HttpError

promise
Get Signature

get promise(): Promise<TransformedReturnType<T>>

Defined in: packages/js-utils/src/services/http-client-mixin/http-request.class.ts:17

The promised raw or transformed result of the endpoint function. Can be awaited.

Returns

Promise<TransformedReturnType<T>>

result
Get Signature

get result(): Awaited<ReturnType<T["function"]>>

Defined in: packages/js-utils/src/services/http-client-mixin/http-request.class.ts:44

The raw result of the endpoint function.

Returns

Awaited<ReturnType<T["function"]>>

status
Get Signature

get status(): HttpRequestStatus

Defined in: packages/js-utils/src/services/http-client-mixin/http-request.class.ts:21

The status of the request.

Returns

HttpRequestStatus

transformedResult
Get Signature

get transformedResult(): Awaited<ReturnType<T["transformer"]>>

Defined in: packages/js-utils/src/services/http-client-mixin/http-request.class.ts:53

The transformed result of the endpoint function.

Returns

Awaited<ReturnType<T["transformer"]>>

Methods

abort()

abort(): void

Defined in: packages/js-utils/src/services/http-client-mixin/http-request.class.ts:40

Aborts the request. Does nothing if the request has already resolved.

Returns

void

setError()

setError(error): void

Defined in: packages/js-utils/src/services/http-client-mixin/http-request.class.ts:36

Sets the error of the request.

Parameters
error

HttpError

The error.

Returns

void

setResult()

setResult(result): void

Defined in: packages/js-utils/src/services/http-client-mixin/http-request.class.ts:49

Sets the raw result of the endpoint function.

Parameters
result

Awaited<ReturnType<T["function"]>>

The new raw result to save.

Returns

void

setStatus()

setStatus(status): void

Defined in: packages/js-utils/src/services/http-client-mixin/http-request.class.ts:26

Sets the status of the request.

Parameters
status

HttpRequestStatus

The status.

Returns

void

setTransformedResult()

setTransformedResult(result): void

Defined in: packages/js-utils/src/services/http-client-mixin/http-request.class.ts:58

Sets the transformed result of the endpoint function.

Parameters
result

Awaited<ReturnType<T["transformer"]>>

The new transformed result to save.

Returns

void


PrivateEndpointParams<TArgs>

Defined in: packages/js-utils/src/services/http-client-mixin/types.ts:44

A set of parameters available internally when the endpoint is invoked.

Type Parameters

TArgs

TArgs extends EndpointFunctionArgs = void

Properties

args

args: TArgs

Defined in: packages/js-utils/src/services/http-client-mixin/types.ts:48

The arguments to be passed to the endpoint function.

signal

signal: AbortSignal

Defined in: packages/js-utils/src/services/http-client-mixin/types.ts:52

An AbortSignal that can be used to cancel the request.

Type Aliases

EndpointFunction()<TArgs>

EndpointFunction<TArgs> = (params) => Promise<any>

Defined in: packages/js-utils/src/services/http-client-mixin/types.ts:60

An endpoint function that will be called when the endpoint is invoked.

Type Parameters

TArgs

TArgs extends EndpointFunctionArgs = void

Parameters

params

PrivateEndpointParams<TArgs>

The EndpointParams of the invoked endpoint.

Returns

Promise<any>

A promise of the response from the server.


EndpointFunctionArgs

EndpointFunctionArgs = Record<string, any> | void

Defined in: packages/js-utils/src/services/http-client-mixin/types.ts:29


Endpoints

Endpoints = Record<string, EndpointDefinition>

Defined in: packages/js-utils/src/services/http-client-mixin/types.ts:95

The set of endpoints to be used by the client.


ErrorHandler

ErrorHandler = object

Defined in: packages/js-utils/src/services/http-client-mixin/types.ts:8

Defines how the client should handle errors.

Properties

continue?

optional continue: boolean

Defined in: packages/js-utils/src/services/http-client-mixin/types.ts:26

Whether the client should continue to call subsequent error handlers after this one.

Default
false;
function()

function: (error) => void | Promise<void>

Defined in: packages/js-utils/src/services/http-client-mixin/types.ts:14

The function to be called when an error occurs.

Parameters
error

The error.

HttpError | unknown

Returns

void | Promise<void>

A promise that resolves when the error has been handled.

statusFilter()?

optional statusFilter: (status) => boolean

Defined in: packages/js-utils/src/services/http-client-mixin/types.ts:21

The status code of the response that will trigger this error handler. If left empty, the error handler will be called for all errors.

Parameters
status

number

The status code.

Returns

boolean

Whether this status code should


HttpRequestStatus

HttpRequestStatus = typeof HttpRequestStatus[keyof typeof HttpRequestStatus]

Defined in: packages/js-utils/src/services/http-client-mixin/types.ts:117

The status of an HTTP request.


TransformedReturnType<T>

TransformedReturnType<T> = T["transformer"] extends undefined ? Awaited<ReturnType<T["function"]>> : Awaited<ReturnType<NonNullable<T["transformer"]>>>

Defined in: packages/js-utils/src/services/http-client-mixin/types.ts:128

Type Parameters

T

T extends EndpointDefinition

Variables

HttpRequestStatus

const HttpRequestStatus: object

Defined in: packages/js-utils/src/services/http-client-mixin/types.ts:117

The status of an HTTP request.

Type declaration

aborted

readonly aborted: "aborted" = 'aborted'

error

readonly error: "error" = 'error'

pending

readonly pending: "pending" = 'pending'

success

readonly success: "success" = 'success'

Functions

createHttpRequest()

createHttpRequest<TEndpointDef>(endpointDef, promise, abortController): HttpRequest<TEndpointDef>

Defined in: packages/js-utils/src/services/http-client-mixin/http-request.class.ts:61

Type Parameters

TEndpointDef

TEndpointDef extends EndpointDefinition<never, EndpointFunction<never>, any>

Parameters

endpointDef

TEndpointDef

promise

Promise<TransformedReturnType<TEndpointDef>>

abortController

AbortController

Returns

HttpRequest<TEndpointDef>


defineEndpoint()

defineEndpoint<TArgs, TFunction, TTransformedResult>(definition): EndpointDefinition<TArgs, TFunction, TTransformedResult>

Defined in: packages/js-utils/src/services/http-client-mixin/http-client.utils.ts:25

A helper function to create an endpoint definition in a type-safe way.

Type Parameters

TArgs

TArgs extends EndpointFunctionArgs = void

TFunction

TFunction extends EndpointFunction<TArgs> = EndpointFunction<TArgs>

TTransformedResult

TTransformedResult = Awaited<ReturnType<TFunction>>

Parameters

definition

EndpointDefinition<TArgs, TFunction, TTransformedResult>

The endpoint definition.

Returns

EndpointDefinition<TArgs, TFunction, TTransformedResult>

The endpoint definition.


HttpClientMixin()

HttpClientMixin<TEndpoints>(options): HttpClient<TEndpoints>

Defined in: packages/js-utils/src/services/http-client-mixin/http-client.service-mixin.ts:69

A mixin that adds HTTP client functionality to a class. Can be used to create a strongly typed HTTP client.

Type Parameters

TEndpoints

TEndpoints extends Endpoints

The set of Endpoints to register with the HTTP client.

Parameters

options

HttpClientOptions<TEndpoints>

The options for the HTTP client.

Returns

HttpClient<TEndpoints>

Example

import { HttpClientMixin, defineEndpoint } from '@spuxx/js-utils';
// Define your endpoints
const endpoints = {
getRandomJoke: defineEndpoint({
function: async () => {
const response = await fetch('https://api.chucknorris.io/jokes/random');
},
transformer: async (response: Response}): string => {
const json = await response.json();
return json.value;
},
}),
getSpecificJoke: defineEndpoint<{ id: string}>({
function: async ({ args }) => {
const response = await fetch(`https://api.chucknorris.io/jokes/${args.id}`);
},
transformer: async (response: Response): string => {
const json = await response.json();
return json.value;
},
}),
}
// Create your client
class HttpClient extends HttpClientMixin({ endpoints }) {}
// Use your client
const randomJoke = await HttpClient.getRandomJoke().promise;
console.log(joke); // Chuck Norris can divide by zero.
const specificJoke = await HttpClient.getSpecificJoke({ args: { id: '123' } }).promise;
console.log(specificJoke); // Chuck Norris can divide by zero.
// Invoking an endpoint returns an `HttpRequest` object that offers various
// methods to interact with the request
const request = HttpClient.getRandomJoke();
request.abort();
console.log(request.status); // 'aborted'

transformFetchJson()

transformFetchJson<TResult>(response): Promise<TResult>

Defined in: packages/js-utils/src/services/http-client-mixin/http-client.utils.ts:15

A very simple transformer that will transform the response from a fetch call into a JSON object and cast it to the specified type. Intended for use with defineEndpoint.

Type Parameters

TResult

TResult

Parameters

response

Response

The response from a fetch call.

Returns

Promise<TResult>

The transformed JSON object.

Example

const endpoint = defineEndpoint({
function: async (): Response => {
return fetch('https://example.com/api/users');
},
transform: transformFetchJson<User[]>,