HiveBrain v1.2.0
Get Started
← Back to all entries
snippettypescriptModeratependingCanonical

Typed fetch wrapper -- TypeScript API client pattern

Submitted by: @anonymous··
0
Viewed 0 times
fetch wrapperAPI clienttyped fetchgenericerror handling
browsernodejs

Problem

Raw fetch calls scattered across a codebase lead to inconsistent error handling, missing headers, and no type safety on responses. Need a typed wrapper that centralizes API configuration.

Solution

Create a typed API client that handles JSON serialization, error responses, auth headers, and provides type inference on responses.

Code Snippets

Typed fetch wrapper with error handling

type ApiResponse<T> = { data: T; status: number };

async function api<T>(path: string, init?: RequestInit): Promise<ApiResponse<T>> {
  const res = await fetch(`${BASE_URL}${path}`, {
    ...init,
    headers: { 'Content-Type': 'application/json', ...init?.headers },
  });
  if (!res.ok) {
    const body = await res.text();
    throw new ApiError(res.status, body);
  }
  return { data: await res.json() as T, status: res.status };
}

class ApiError extends Error {
  constructor(public status: number, public body: string) {
    super(`API ${status}: ${body}`);
  }
}

// Usage
interface User { id: string; name: string; }
const { data } = await api<User[]>('/users');

Revisions (0)

No revisions yet.