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 |
|---|---|---|
|
| The resource that you wish to fetch. Can be a URL string or a Request object. |
|
| Optional configuration object containing any custom settings that you want to apply to the request (method, headers, body, etc.). |
Return Value
Returns a
Promise<JSON>which resolves with the parsed JSON data from the response body.The generic type parameter
JSONallows the caller to define the expected shape of the response for type safety.
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
fetcheruses the nativefetchAPI to send the HTTP request.After awaiting the response, it directly calls
res.json()to parse the response body as JSON.There is no explicit error handling; if the fetch fails or the response is not valid JSON, the returned Promise will reject.
The function is generic, defaulting to
anyif no type parameter is provided.
Interaction with Other Parts of the System
This utility function serves as a low-level data fetching helper in the data access layer.
It can be used throughout the application wherever JSON data needs to be retrieved via HTTP requests.
It abstracts away the repetitive pattern of calling
fetchand parsing JSON, enabling other modules to write cleaner and more concise asynchronous code.Since it returns a Promise, it integrates naturally with async/await syntax and Promise chains used throughout the system.
It can be extended or wrapped in higher-level API service modules that handle additional concerns such as authentication tokens, error handling, or caching.
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.