Tsentials http

From senrecep/tsentials · View interactive version

Tsentials http is an AI agent skill from the GitHub repository senrecep/tsentials. Use when making HTTP calls that should return Result<T> instead of throwing: fetchResult const object with get/post/put/patch/delete methods, RequestBuilder for fluent header/query-param/body construction with .send<T>(), httpStatusToError for status-to-AppError mapping, extractErrorDescription for

How to use this skill

Skill file

tsentials/http

Fetch API wrapper that returns Result<T> instead of throwing on 4xx/5xx responses. Never catch fetch exceptions again.

Installation

npm install tsentials

Import

import { fetchResult, RequestBuilder, httpStatusToError, extractErrorDescription } from 'tsentials/http';
import { computeETag, formatETag, notModified, checkIfMatch } from 'tsentials/http';
import { toProblemDetails, toProblemResponse, resultToResponse } from 'tsentials/http';
import { isBlockedAddress } from 'tsentials/http';

fetchResult — direct fetch wrapper

fetchResult is a const object with HTTP method functions — not a generic function. Each method returns Promise<Result<T>>.

import { fetchResult } from 'tsentials/http';

// GET
const result = await fetchResult.get<User>('https://api.example.com/users/1');

// POST with JSON body
const created = await fetchResult.post<Order>('https://api.example.com/orders', newOrder);

// PUT with JSON body
const updated = await fetchResult.put<User>('https://api.example.com/users/1', userDto);

// PATCH with JSON body
const patched = await fetchResult.patch<User>('https://api.example.com/users/1', partial);

// DELETE
const deleted = await fetchResult.delete('https://api.example.com/users/1');

// 2xx → Result.success(T), 4xx/5xx → Result.failure(AppError)
if (result.ok) {
  console.log(result.value); // User
} else {
  console.log(result.errors[0]?.description);
}

fetchResult Method Signatures

fetchResult.get<T>(url: string | URL, init?: RequestInit): Promise<Result<T>>
fetchResult.post<T>(url: string | URL, body: unknown, init?: RequestInit): Promise<Result<T>>
fetchResult.put<T>(url: string | URL, body: unknown, init?: RequestInit): Promise<Result<T>>
fetchResult.patch<T>(url: string | URL, body: unknown, init?: RequestInit): Promise<Result<T>>
fetchResult.delete<T = void>(url: string | URL, init?: RequestInit): Promise<Result<T>>

POST, PUT, and PATCH automatically set Content-Type: application/json and stringify the body.

A 2xx JSON response with an empty or null body is a NotFound failure (code NotFound), except for fetchResult.delete, which succeeds with undefined. 204/205 and non-JSON responses are void successes. A body that is not read (204/205, a non-JSON 2xx or error response) is cancelled so the connection is released.

Text and binary bodies

Set responseType ('text', 'blob' or 'arrayBuffer') to read a 2xx body as a string, Blob or ArrayBuffer whatever its content type; the default 'json' keeps the rules above. An empty body or 204/205 gives an empty value, not NotFound. Error responses go through the same ProblemDetails parsing, a read error is an Unexpected failure with the response status, a timeout is Http.Timeout, and the caller's abort still rejects.

const csv = await fetchResult.get<string>('/export.csv', { responseType: 'text' });
const pdf = await RequestBuilder.get('/invoice/7').responseType('blob').send<Blob>();
const bytes = await fetchResult.post<ArrayBuffer>('/render', { id: 7 }, { responseType: 'arrayBuffer' });

RequestBuilder — fluent request construction

For requests with multiple headers, query parameters, or custom bodies. The terminal method is .send<T>().

import { RequestBuilder } from 'tsentials/http';

// GET with headers and query params
const result = await RequestBuilder.get('https://api.example.com/users')
  .header('Authorization', `Bearer ${token}`)
  .header('X-Correlation-Id', correlationId)
  .query('page', '1')
  .query('limit', '20')
  .send<User[]>();

// Route placeholders, array and Date query values
const posts = await RequestBuilder.get('https://api.example.com/users/{id}/posts')
  .route('id', userId)                 // URL-encoded
  .query('tag', ['news', 'tech'])      // tag=news&tag=tech
  .query('since', new Date(2026, 0, 1)) // ISO 8601
  .send<Post[]>();

// POST with JSON body
const posted = await RequestBuilder.post('https://api.example.com/orders')
  .header('Authorization', `Bearer ${token}`)
  .json(newOrder)
  .send<Order>();

// PUT
const updated = await RequestBuilder.put(`https://api.example.com/users/${id}`)
  .header('Authorization', `Bearer ${token}`)
  .json(userDto)
  .send<User>();

// PATCH
const patched = await RequestBuilder.patch(`https://api.example.com/users/${id}`)
  .header('Authorization', `Bearer ${token}`)
  .json(partial)
  .send<User>();

// DELETE — send<T>() expects a value: an empty/null JSON body is a NotFound failure
// (use fetchResult.delete for a DELETE that may answer with an empty body)
const deleted = await RequestBuilder.delete(`https://api.example.com/users/${id}`)
  .header('Authorization', `Bearer ${token}`)
  .send<DeleteReceipt>();

// Raw (non-JSON) body on POST/PUT/PATCH — .body() bypasses JSON serialization entirely
const uploaded = await RequestBuilder.post('https://api.example.com/upload')
  .header('Content-Type', 'text/plain')
  .body(rawText)
  .send<UploadResult>();

.json(value) stringifies value and sets Content-Type: application/json. .body(raw) sends raw (a BodyInit — string, Blob, FormData, ArrayBuffer, ...) untouched, with no assumption that it's JSON — send<T>() never runs JSON.parse/JSON.stringify on a .body() payload, so it can't throw on non-JSON content. Calling .json() after .body() (or vice versa) simply replaces whichever was set last.

RequestBuilder API

| Static Factory | Returns |

|----------------|---------|

| RequestBuilder.get(url) | RequestBuilder |

| RequestBuilder.post(url) | RequestBuilder |

| RequestBuilder.put(url) | RequestBuilder |

| RequestBuilder.patch(url) | RequestBuilder |

| RequestBuilder.delete(url) | RequestBuilder |

| Builder Method | Description |

|----------------|-------------|

| .header(name, value) | Add a request header; the same name again adds another value (Content-Type is replaced) |

| .query(name, value) / .query(record) | Append query string parameters; an array repeats the key (tag=a&tag=b), a Date is sent as ISO 8601, null/undefined record values are skipped |

| .route(name, value) / .route(record) | Replace every {name} placeholder in the URL with the URL-encoded value; a missing placeholder or a null/undefined value makes send() a Validation failure (RequestBuilder.RouteParameterNotFound, RequestBuilder.RouteValueRequired) with no request sent |

| .json(body) | Set body as JSON + Content-Type header |

| .body(body: BodyInit) | Set raw body |

| .idempotencyKey(key?, { idempotencyKeyGenerator }?) | Set Idempotency-Key (a UUID, or your generator's result, created once when omitted and validated like an explicit key; every send() reuses it) |

| .send<T>() | Send request, returns Promise<Result<T>> |


Cancellation and timeout

fetchResult and RequestBuilder accept an AbortSignal and a request timeout.

const ctrl = new AbortController();

await fetchResult.get<User>('/users/42', { signal: ctrl.signal, timeout: 5_000 });

await RequestBuilder.get('/users')
  .query({ limit: 10, q: undefined })   // record form; null/undefined values are skipped
  .timeout(5_000)
  .signal(ctrl.signal)
  .send<User[]>();

Idempotency keys and retries

import { withIdempotencyKey, idempotentRetryClassifier, HttpErrorMetadataKeys } from 'tsentials/http';

const init = withIdempotencyKey({ method: 'POST', body });   // one key for every retry of this operation
await ResiliencePolicy.create()
  .withRetry({ shouldRetry: idempotentRetryClassifier('POST', true) })
  .execute((signal) => fetchResult.send<Order>('/orders', { ...init, signal }));

Conditional requests (ETag, 304, If-Match)

import { computeETag, formatETag, notModified, checkIfMatch } from 'tsentials/http';

// GET: answer 304 when the client's copy is current
async function getItem(request: Request): Promise<Response> {
  const item = await load();
  const etag = formatETag(item.version);                 // '"7"'; computeETag(body) hashes content
  const headers = { 'cache-control': 'max-age=60' };
  return notModified(request, { etag, lastModified: item.updatedAt }, headers)
    ?? Response.json(item, { headers: { ...headers, etag } });
}

// PUT/PATCH/DELETE: optimistic concurrency
async function updateItem(request: Request): Promise<Response> {
  const item = await load();                             // null when it does not exist
  const rejected = checkIfMatch(request, item && { etag: formatETag(item.version) }, { required: true });
  if (rejected) return rejected;                         // 400, 412 or 428 problem+json
  // ... write, passing the version as a concurrency token
}

Problem responses (server side)

import { resultToResponse, toProblemDetails, toProblemResponse } from 'tsentials/http';

return resultToResponse(await createUser(input));        // 200 JSON, 204 for Result.ok(), or problem+json
return toProblemResponse([Err.notFound('User.NotFound', 'User 7 was not found.')], {
  extensions: { traceId },
  headers: { 'cache-control': 'no-store' },
});
const body = toProblemDetails(errors);                    // the plain object

Blocked addresses (SSRF checks)

isBlockedAddress(address) returns true for an IP literal that a server-side request to a user-supplied URL must not reach. The ranges are those of the CSharpEssentials SSRF guard: unspecified, loopback, private (RFC 1918), CGNAT (100.64.0.0/10), link-local (including the 169.254.169.254 metadata endpoint), unique local (fc00::/7), multicast, broadcast and reserved, and the documentation and benchmark ranges. An IPv4 address inside IPv6 (::ffff:127.0.0.1, ::10.0.0.1, 64:ff9b::a9fe:a9fe, 2002:c0a8:101::) is checked as IPv4 too.

import { lookup } from 'node:dns/promises';
import { isBlockedAddress } from 'tsentials/http';

async function assertPublicHost(url: URL): Promise<void> {
  const host = url.hostname.replace(/^\[|\]$/g, ''); // URL keeps the brackets of an IPv6 literal
  const addresses = await lookup(host, { all: true }); // an IP literal comes back as is
  if (addresses.length === 0 || addresses.some((a) => isBlockedAddress(a.address))) {
    throw new Error(`Blocked outbound host ${url.hostname}`);
  }
}

await assertPublicHost(new URL(target));
const result = await fetchResult.get<Data>(target, { redirect: 'manual' });

Chaining with ResultAsync

import { fromAsync } from 'tsentials/result';
import { Err } from 'tsentials/errors';

const profile = await fromAsync(
  RequestBuilder.get('https://api.example.com/users/me')
    .header('Authorization', `Bearer ${token}`)
    .send<User>(),
)
  .ensure(user => user.isActive, Err.validation('User.Inactive', 'Account is not active.'))
  .map(user => user.profile)
  .match(
    profile => profile,
    () => null,
  );

Error Mapping

HTTP errors are automatically mapped to AppError with descriptive codes via httpStatusToError():

| HTTP Status | ErrorType | Notes |

|-------------|-----------|-------|

| 400 | Validation | Bad Request |

| 401 | Unauthorized | |

| 403 | Forbidden | |

| 404 | NotFound | |

| 409 | Conflict | |

| 410 | NotFound | Gone — mapped to NotFound |

| 422 | Validation | Unprocessable Entity — mapped to Validation |

| 429 | Conflict | Too Many Requests — mapped to Conflict |

| 5xx | Unexpected | All server errors |

| Other | Failure | Unmapped status codes |

| Network error | Unexpected | TypeError from fetch |

| Malformed 2xx JSON body | Validation | Code SyntaxError |

| Unserializable JSON request body | Validation | Code TypeError, nothing sent |

The error code format is Http.{status} (e.g., Http.404, Http.500).

A ProblemDetails body overrides the code (problemDetailsToErrors):

// 404 body: {"title":"Not Found","status":404,"detail":"No user with id 42.","errorCodes":["User.NotFound"]}
// AppError { code: 'User.NotFound', description: 'No user with id 42.', type: 'NotFound' }

Only when the body has neither does the code fall back to Http.{status}.


httpStatusToError / extractErrorDescription

Exported utility functions for custom HTTP handling:

import { httpStatusToError, extractErrorDescription } from 'tsentials/http';

// Manual status-to-error mapping
const error = httpStatusToError(404, 'User not found');
// AppError { code: 'Http.404', description: 'User not found', type: 'NotFound' }

// Extract error description from a ProblemDetails (RFC 9457) response
const description = await extractErrorDescription(response);
// Reads `detail` or `title` from application/problem+json or application/json body

Best Practices

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.