Registry / http-networking / typesafe-api-call

typesafe-api-call

JSON →
library5.1.2jsnpmunverified

typesafe-api-call is a minimalistic JavaScript library designed to streamline API interactions by enforcing typesafety and a functional programming paradigm. It abstracts away traditional exception handling, instead ensuring that every API call resolves to an explicit `APISuccess` or `APIFailure` result, compelling developers to handle both successful and unsuccessful outcomes distinctly. The library is currently on version 5.1.2 and appears to have an active release cadence, with recent patches and new features like `callWithRetries` introduced in minor versions. A key differentiator is its emphasis on functional results over exceptions, promoting predictable state management. It also integrates seamlessly with complementary tools like `type-decoder` and `type-crafter` to facilitate YAML-driven type and decoder generation, further enhancing end-to-end typesafety for API responses.

npm install typesafe-api-call
INSTALL
IMPORT
SIG · TYPESAFE-API-CALL
T
typesafe-api-call
http-networkingjavascriptv5.1.2
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

APICaller
✓ import { APICaller } from 'typesafe-api-call';
✗ const APICaller = require('typesafe-api-call').APICaller;
ESM is the primary module system. While `packageJson.main` was patched in v5.1.1 for CJS compatibility, direct ESM imports are recommended for modern Node.js and bundlers.
APIResponse
✓ import { APIResponse } from 'typesafe-api-call';
✗ import APIResponse from 'typesafe-api-call';
APIResponse is a named export, not a default export. Ensure correct destructuring.
APISuccess
✓ import { APISuccess } from 'typesafe-api-call';
✗ import { APISuccess } from 'typesafe-api-call/lib';
The library exports directly from its root. Do not attempt to import from internal paths like `/lib` as these are not stable API surfaces.
APIRequest (type)
✓ import type { APIRequest } from 'typesafe-api-call';
For type-only imports, use `import type` to ensure they are stripped from the JavaScript output, preventing potential runtime errors in certain environments.

Demonstrates a basic GET API call using `APICaller`, showing how to define a request, provide decoding functions, and handle the explicit `APISuccess` or `APIFailure` result.

import { APICaller, APIResponse, type APIRequest, APISuccess } from 'typesafe-api-call'; interface Post { userId: number; id: number; title: string; body: string; } const serverEndpoint = 'https://jsonplaceholder.typicode.com'; async function getAllPosts(): Promise<APIResponse<Post[], unknown>> { const apiRequest: APIRequest = { url: new URL(`${serverEndpoint}/posts`), method: 'GET' }; // Using an anonymous function for decoding. In a real app, you'd use a dedicated decoder. const apiResponse = await APICaller.call( apiRequest, (successResponse: unknown) => successResponse as Post[], // Simulate decoding (errorResponse: unknown) => errorResponse // Error handling can also include decoding ); return apiResponse; } async function runExample() { console.log('Fetching all posts...'); const getAllPostResult = await getAllPosts(); if (getAllPostResult instanceof APISuccess) { console.log('Successfully fetched posts:', getAllPostResult.data.slice(0, 2)); } else { console.log('Failed to fetch posts:', getAllPostResult.error); } } runExample();
Debug
Known issues
breakingPrior to version 5.1.1, users utilizing CommonJS environments or specific bundler configurations might have encountered issues resolving the main package entrypoint.
fix
Upgrade to `typesafe-api-call@^5.1.1` or later to ensure proper module resolution across different environments. Prefer ESM imports where possible.
affects: <5.1.1
gotchaThis library replaces traditional `try/catch` blocks for network and API errors with a functional result pattern (`APISuccess` | `APIFailure`). Direct exception handling for API calls will bypass this pattern.
fix
Always check the `APIResponse` object using `if (response instanceof APISuccess)` or `if (response instanceof APIFailure)` to handle outcomes, rather than relying on `try/catch` for HTTP-level errors.
affects: >=1.0.0
gotchaThe `call` method requires two decoding functions: one for a successful API response and one for an erroneous API response. If these are not provided or implemented correctly, the `data` or `error` properties within `APISuccess` or `APIFailure` will remain `unknown`.
fix
Implement robust decoding logic within the success and error callbacks passed to `APICaller.call`. Consider using complementary libraries like `type-decoder` for structured decoding.
affects: >=1.0.0
gotchaThe `url` property in `APIRequest` strictly expects a `URL` object, not a string. Passing a string will result in a runtime TypeError.
fix
Ensure that the `url` property of your `APIRequest` object is always instantiated as `new URL('your-api-endpoint')`.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: APICaller.call is not a function
Incorrect module import, especially in CommonJS environments prior to v5.1.1, or attempting to access `call` on an undefined `APICaller`.
fix
Ensure you are using `import { APICaller } from 'typesafe-api-call';` (ESM) and have updated to `typesafe-api-call@^5.1.1` or later. Verify that `APICaller` is correctly imported and not `undefined`.
ReferenceError: APISuccess is not defined
The `APISuccess` class was not correctly imported from the `typesafe-api-call` package.
fix
Add `import { APISuccess } from 'typesafe-api-call';` to the top of your file. Remember it's a named export.
Property 'data' does not exist on type 'unknown'.
This error occurs when you attempt to access properties like `data` or `error` on the `APISuccess` or `APIFailure` instances without properly defining the type parameters (`T` and `U`) in `APIResponse<T, U>`, or without implementing the decoding functions correctly.
fix
Ensure your `APIResponse` is correctly typed (e.g., `APIResponse<MyDataType, ErrorType>`) and that the success/error decoding functions passed to `APICaller.call` return the expected types. The example's `(successResponse: unknown) => successResponse as Post[]` is a minimal cast; for production, implement actual type guards or decoders.
Upgrade
Version history
5.1.2latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
18 hits · last 30 days
node
16
OpenAI (training)
1
Resources
typesafe-api-call — npm install typesafe-api-call · libregistry