fetch.ts

Overview

fetch.ts defines a simple, reusable utility function named fetcher that wraps the native fetch API to perform HTTP requests and automatically parse the response as JSON. This abstraction streamlines data fetching operations by encapsulating the common pattern of making a request and parsing the JSON response into a single asynchronous function.

The function is generic, allowing callers to specify the expected JSON response type for improved type safety and better integration with TypeScript-enabled codebases.


Function Details

fetcher<JSON = any>(input: RequestInfo, init?: RequestInit): Promise<JSON>

Description

fetcher is an asynchronous function that sends an HTTP request using the browser's native fetch API. It accepts the standard parameters of fetch, waits for the response, and then returns the parsed JSON body.

Parameters

Parameter

Type

Description

input

RequestInfo

The resource that you wish to fetch. Can be a URL string or a Request object.

init

RequestInit

Optional configuration object containing any custom settings that you want to apply to the request (method, headers, body, etc.).

Return Value

Usage Example

interface User {
  id: number;
  name: string;
  email: string;
}

async function getUser(userId: number): Promise<User> {
  const url = `https://api.example.com/users/${userId}`;
  const user = await fetcher<User>(url);
  return user;
}

getUser(1).then(user => {
  console.log(user.name);
});

Implementation Details


Interaction with Other Parts of the System


Mermaid Diagram

flowchart TD
    A[fetcher function] --> B[Calls fetch(input, init)]
    B --> C[Awaits Response]
    C --> D[Calls res.json()]
    D --> E[Returns Promise<JSON>]

Summary

The fetch.ts file provides a minimal yet powerful generic utility function, fetcher, that wraps the native fetch API and automatically parses JSON responses. It simplifies HTTP interactions, improves code readability, and enhances type safety for JSON data fetching across the application. Its design makes it a foundational utility in the data access layer, promoting reuse and consistency throughout the software project.