@ololoepepe/api-wrapper
v0.4.3
Published
A wrapper around your API calls
Readme
@ololoepepe/api-wrapper
A small, transport-agnostic, fully typed wrapper around your API calls. It coordinates three pluggable pieces — a transport (request/response calls), an authenticator (authentication-data lifecycle), and a realtime transport (subscriptions with automatic reconnection) — behind one consistent object with built-in authentication, session-retry, and reconnect handling.
You bring the concrete implementations (HTTP, WebSocket, Firestore, gRPC, raw TCP, mocks, …) by subclassing the abstract base classes; the wrapper orchestrates them.
Features
- Types declared once, per endpoint. A request carries — at the type level —
what it answers with, so
callMethod()infers the whole result from the request alone. No type arguments at call sites. - Protocol-agnostic. The library knows nothing about HTTP verbs, paths or status codes; you describe the shape of a request through a contract.
- Optional runtime validation, with the domain type inferred from the schema — write it once, get both the check and the types.
- Never throws on a call.
callMethod()resolves with a discriminated result:ok, the unpackeddata, theerror, and the raw protocol response so headers, status codes and the like stay reachable. - Transparent authentication with concurrent-call de-duplication (only one authentication runs at a time per authenticator).
- Automatic re-authentication and one-shot retry on session-expired errors, for both request/response calls and realtime subscriptions.
- Realtime subscriptions with an exponential-backoff reconnect state machine.
- Structured errors (
ApiError+ApiErrorCode) surfaced both in the result and aserrorevents. - Isomorphic: runs in Node.js and in the browser, with a tree-shakeable ESM
browser build and a UMD bundle for plain
<script>use.
Requirements
- Node.js >= 24
- TypeScript >= 5 (the package ships its own declarations)
- Browsers from 2020 and newer (for the browser build)
Installation
npm install @ololoepepe/api-wrapperQuick start
1. Describe your API once
The contract fixes everything that does not vary from request to request: what authentication data looks like, the shape of a request, how the protocol wraps a payload into a response, and what errors the transport rejects with.
import type {
ApiContract,
ApiRequest,
ApiResponseEnvelope,
ApiSubscription
} from '@ololoepepe/api-wrapper';
import type {AxiosError, AxiosResponse} from 'axios';
// What a request looks like for this protocol.
type HttpRequest<TResponseData = unknown> = ApiRequest<TResponseData> & {
data?: unknown;
headers?: Record<string, string>;
method: 'delete' | 'get' | 'patch' | 'post';
url: string;
};
// What a subscription looks like for this protocol.
type ChannelSubscription<TCallbacks = unknown> = ApiSubscription<TCallbacks> & {
channel: string;
};
// How the protocol wraps a payload into a full response.
interface AxiosResponseEnvelope extends ApiResponseEnvelope {
readonly response: AxiosResponse<this['responseData']>;
}
interface MyApi extends ApiContract {
authenticationData: {tokenAccess: string};
error: AxiosError;
request: HttpRequest;
response: AxiosResponseEnvelope;
subscription: ChannelSubscription;
}2. Declare each endpoint once
An endpoint is a plain function whose return type names the domain type. That is the only place a type is written down.
export const authenticate = (email: string, password: string): HttpRequest<Session> => ({
data: {email, password},
method: 'post',
url: '/auth/users/authenticate'
});
export const listUsers = (): HttpRequest<User[]> => ({
isPrivate: true,
method: 'get',
url: '/users'
});
export const watchUsers = (): ChannelSubscription<{onChange: (user: User) => void}> => ({
channel: 'users',
isPrivate: true
});3. Implement the three pieces
import {ApiAuthenticator, ApiRealtimeTransport, ApiTransport} from '@ololoepepe/api-wrapper';
class MyTransport extends ApiTransport<MyApi> {
// Return the protocol's full response, not the payload.
override async callMethod({authenticationData, request}) { … }
// Unpack the payload out of it. May be async.
override getResponseData(response) { return response.data; }
override isAuthenticationFailedError(error) { … }
override isSessionExpiredError(error) { … }
}
class MyAuthenticator extends ApiAuthenticator<MyApi> {
override async authenticate({previousAuthenticationData, wrapper}) { … }
override async loadAuthenticationData() { … }
override async saveAuthenticationData(authenticationData) { … }
}
class MyRealtimeTransport extends ApiRealtimeTransport<MyApi> {
override connect({onConnect, onDisconnect, wrapper}) { … }
override disconnect() { … }
override subscribe({authenticationData, callbacks, onError, onSubscribe, onUnsubscribe, subscription}) { … }
override unsubscribe({subscription}) { … }
override isSessionExpiredError(error) { … }
}4. Call it
import {ApiWrapper} from '@ololoepepe/api-wrapper';
const api = new ApiWrapper<MyApi>({
authenticator: new MyAuthenticator(),
realtimeTransport: new MyRealtimeTransport(),
transport: new MyTransport()
});
api.addEventListener('error', event => {
console.error('API error:', (event as CustomEvent).detail);
});
const result = await api.callMethod(authenticate(email, password));
if (result.ok) {
result.data; // ^? Session
result.response.status; // ^? number — the raw axios response
result.response.headers['x-trace-id'];
} else {
result.error; // ^? ApiError | AxiosError
}
const users = await api.callMethod(listUsers()); // data: User[]
// Callbacks are checked against the shape the subscription declares.
const unsubscribe = api.subscribe(watchUsers(), {
onChange: user => console.log(user.name)
});Nothing above needs a type annotation or a type argument at the call site.
How it works
Requests
callMethod(request) takes one value that describes everything: what to
perform, whether it is private, and — at the type level — what it answers with.
isPrivate on the request controls authentication:
isPrivateabsent orfalse— the call is made without authentication data.isPrivate: true— the wrapper first resolves authentication data (loading it, or authenticating if none is stored) and passes it to the transport. If the transport reports a session-expired error (isSessionExpiredError), the wrapper re-authenticates and retries the call once.
The call never rejects. It resolves with:
{ok: true, data: TResponseData, error: null, response: TResponse}
{ok: false, data: null, error: TError, response: null}data is what ApiTransport#getResponseData() unpacked; response is whatever
ApiTransport#callMethod() returned, untouched. error is ApiError or the
contract's own error type. Failures are also dispatched as an error event.
How the types line up
Two type-level markers do the work, and neither exists at runtime:
- A request carries its response type.
ApiRequest<TResponseData>tags a request;callMethod()reads the tag back off the value you pass in. - A subscription carries its callbacks type.
ApiSubscription<TCallbacks>does the same forsubscribe().
The contract's response field is a small type-level function from the payload
type to the protocol's full response — that is why AxiosResponse<…> is written
once per client rather than at every endpoint:
interface AxiosResponseEnvelope extends ApiResponseEnvelope {
readonly response: AxiosResponse<this['responseData']>;
}If your transport hands back the payload itself, use the ready-made
ApiPlainResponseEnvelope instead.
The seam, and how to close it: ApiTransport#callMethod() is one function for
every request, so what it returns is genuinely opaque — a brand is a declaration
of intent, not a runtime check. Attach a validator and the boundary is checked
for real; see below.
Validating what the server sends
Any object with this shape fits — the library depends on no validator package:
interface ApiValidator<TValue> {
validate: (data: unknown) => Promise<{ok: false; error: unknown} | {ok: true; value: TValue}>;
}A validator from @ololoepepe/validator
satisfies it as-is; anything else (zod, valibot, hand-rolled) becomes usable by
wrapping it in that shape.
Attach one to a request and the schema becomes the single place the domain type is written:
import {createValidator} from '@ololoepepe/validator';
const userValidator = createValidator({
fields: {
id: {type: 'string'},
role: {type: 'string', values: ['admin', 'user']},
seats: {defaultValue: 1, missingStrategy: 'default', type: 'number'}
},
type: 'object'
});
const getUser = (id: string): HttpRequest<ApiValidatorValue<typeof userValidator>> => ({
isPrivate: true,
method: 'get',
responseValidator: userValidator,
url: `/users/${id}`
});
const result = await api.callMethod(getUser('u1'));
if (result.ok) {
result.data.id; // ^? string
result.data.role; // ^? 'admin' | 'user' — a literal union, from `values`
result.data.seats; // ^? number — the default was filled in
}ApiValidatorValue<typeof v> reads the type back off the validator, so the
annotation names nothing the schema did not already say. Writing the factory with
satisfies instead of an annotation infers the same type without naming it at
all — a validator always takes precedence over the brand.
A failed validation is an ordinary failure: {ok: false} with an ApiError
carrying ResponseValidationFailed, the validator's own error in
data.originalError, and the offending raw response in data.response. Because
a validator may normalise (defaults, coercions, stripped extras), data is what
the validator produced — the untouched protocol response stays in response.
Validation is entirely optional: a request without responseValidator behaves
exactly as before.
Realtime messages work the same way, with one difference: a subscription
delivers through consumer-provided callbacks whose shape only the transport
knows, so the transport is what runs the validator. Put one on the subscription
and read it back in subscribe():
type ChannelSubscription<TCallbacks = unknown> =
ApiSubscription<TCallbacks, ItemEvent> & {channel: string};
override subscribe({callbacks, onError, subscription}) {
const {messageValidator} = subscription;
const dispatch = async (message: unknown) => {
const validation = await messageValidator?.validate(message);
if (validation && !validation.ok) {
onError(validation.error);
return;
}
callbacks.onMessage(validation ? validation.value : message);
};
…
}Authentication
authenticate() resolves through ApiAuthenticator, then persists the result via
saveAuthenticationData(). Concurrent authentications for the same authenticator
are de-duplicated: overlapping callers await a single in-flight promise. On a
failure the transport recognises as an authentication failure, an ApiError with
code AuthenticationFailed is emitted and thrown.
Unlike callMethod(), authenticate() and getAuthenticationData() reject
on failure.
Realtime & reconnection
subscribe() registers the subscription and connects on demand. On an unexpected
disconnect the wrapper reconnects using exponential backoff and re-subscribes all
active subscriptions once reconnected. When the last subscription is removed it
disconnects. Backoff is configurable:
new ApiWrapper<MyApi>({
authenticator,
realtimeTransport,
transport,
reconnectConfig: {
delay: 1000, // initial delay, ms
delayFactor: 2, // multiplier per attempt
jitter: 0.2, // random share cut off each wait, 0…1
maxDelay: 32000 // upper bound, ms
}
});Each wait is shortened by a random share of itself, up to jitter of it — with
the defaults, the first attempt lands somewhere in 800–1000 ms. That matters when
a service goes down: every client loses the connection at the same moment, and
without the jitter every client comes back at the same moment too, hitting the
service that has just come up with the whole herd at once. Raise it towards 1
to spread them wider (1 means the wait is anything from zero up to the full
delay), or set 0 for exact delays.
The randomness applies to the wait only, never to the backoff sequence behind it:
a shortened wait does not shorten the next one. Since the wait is only ever cut
short, maxDelay stays a real upper bound. A value outside 0…1 is clamped
into it.
Your ApiRealtimeTransport must report every closed connection through the
onDisconnect callback passed to connect() — pass an error for unexpected drops
(which triggers a backoff reconnect) and no argument for clean closes.
For subscriptions flagged isPrivate the wrapper handles authentication for you,
exactly like the request path:
- Before every (re)subscribe the wrapper resolves authentication data and passes
it to
subscribe()asauthenticationData(it isnullfor public subscriptions). Re-resolving each time means a token refreshed elsewhere is always picked up. - Report a failed subscribe attempt through the
onErrorcallback passed tosubscribe(). If the transport classifies it as a session-expired error (isSessionExpiredError), the wrapper re-authenticates and re-subscribes once with a fresh token — the realtime analogue of the request-path retry. - If resolving authentication fails (including the first authentication of a
session), the failure is surfaced through the
errorevent and the subscription is left unestablished — it is never subscribed with a missing token. It is retried on the next reconnect.
If the realtime protocol authenticates through a scheme separate from the
request transport's, the transport can opt out of this built-in mechanism by
setting managesOwnAuthentication to true. The wrapper then resolves
nothing, passes authenticationData: null, and skips the session-expired retry —
isPrivate is still forwarded on the subscription so the transport knows it needs
authenticating, but the transport owns the whole auth lifecycle itself.
Errors
Errors reach you two ways: in the resolved result (ok: false), and as an
error event (a CustomEvent; the error is in event.detail). Because
ApiWrapper extends EventTarget, subscribe with addEventListener('error', …).
API
new ApiWrapper<TContract>({authenticator, realtimeTransport, transport, reconnectConfig?})
Throws ApiError (ParameterNotProvided) if authenticator, realtimeTransport
or transport is missing — a runtime guard that matters for JavaScript callers.
| Member | Description |
| --- | --- |
| callMethod(request) | Perform a request; resolves with an ApiCallResult, never rejects. |
| subscribe(subscription, callbacks) | Subscribe; returns an idempotent unsubscribe function. |
| authenticate() | Force authentication; resolves with the authentication data, rejects on failure. |
| getAuthenticationData() | Load stored auth data, authenticating if there is none. |
| getAuthenticator() / getTransport() | Accessors. |
| error event | CustomEvent; the error (an ApiError or the original error) is in event.detail. |
Contract types
ApiContract—authenticationData,error,request,response,subscription. Extend it and narrow only what you need.ApiRequest<TResponseData>— intersect with your protocol's request shape. Carries the optionalisPrivateflag.ApiSubscription<TCallbacks>— the same for subscriptions.ApiResponseEnvelope— the payload → full-response mapping;ApiPlainResponseEnvelopewhen the response is the payload.ApiValidator/ApiValidationResult— the structural validator slot;ApiValidatorValuereads the type a validator produces.ApiCallResult,ApiRequestResult,ApiResponse,ApiRequestResponseData,ApiSubscriptionCallbacks— helpers, exported for when you need to name a result type yourself.
Abstract base classes
Subclass these; the base implementations throw ApiError
(MethodNotImplemented) so unimplemented methods fail loudly at runtime.
ApiTransport<TContract>—callMethod({authenticationData, request, wrapper}),getResponseData(response),isAuthenticationFailedError(error),isSessionExpiredError(error).ApiAuthenticator<TContract>—authenticate({previousAuthenticationData, wrapper}),loadAuthenticationData(),saveAuthenticationData(authenticationData).ApiRealtimeTransport<TContract>—connect({onConnect, onDisconnect, wrapper}),disconnect(),subscribe({authenticationData, callbacks, onError, onSubscribe, onUnsubscribe, subscription}),unsubscribe({subscription}),isSessionExpiredError(error), and themanagesOwnAuthenticationfield (falseby default; set it totrue— in the constructor or asoverride managesOwnAuthentication = true;— to opt out of the built-in subscription authentication).
ApiError and ApiErrorCode
import {ApiError, ApiErrorCode} from '@ololoepepe/api-wrapper';
new ApiError(code = ApiErrorCode.Unexpected, message = code, data = null);ApiErrorCode is an enum with AuthenticationFailed, MethodNotImplemented,
ParameterNotProvided, RealtimeTransport, ResponseValidationFailed and
Unexpected. ApiError#code is
typed as ApiErrorCode, so comparisons narrow and switch is exhaustive:
if (!result.ok && result.error instanceof ApiError) {
switch (result.error.code) {
case ApiErrorCode.AuthenticationFailed: { … }
…
}
}Module resolution
The package ships three builds, each for a different consumer:
- Types resolve to
dist/node/index.d.ts. - Node resolves to
dist/node/index.js— ES modules fromtsc, untranspiled. - Browser bundlers resolve to
dist/browser/index.js— ES modules transpiled for browsers from 2020 onward. Kept as one file per module rather than a bundle, so a consumer that imports a single export can tree-shake the rest away (the package is marked"sideEffects": false). - A plain
<script src="…">wantsdist/umd/index.js— a UMD bundle exposing the globalapiWrapper, reachable as@ololoepepe/api-wrapper/umd. It is deliberately not on a condition bundlers resolve: a UMD bundle is opaque to tree-shaking and needs CommonJS interop, so bundlers get the ESM build instead.
Both ESM output directories carry their own package.json restating
"type": "module" and mapping the #src/* subpath imports the sources use onto
their sibling files, so nothing in the compiled output points back at
unpublished sources. The UMD directory carries one marking itself CommonJS, so
the wrapper is not parsed as an ES module — while keeping the .js extension,
so any web server serves it with a JavaScript MIME type.
License
UNLICENSED — private package.
