@revas-hq/kit-fetch
v0.0.3
Published
The `@revas-hq/kit-fetch` package provides a flexible way to enhance the `fetch` function with context-aware middleware. This package allows for injecting values like authorization headers and base URLs into fetch requests, making it easier to manage API
Downloads
19
Readme
Kit Fetch Library
The @revas-hq/kit-fetch
package provides a flexible way to enhance the fetch
function with context-aware middleware. This package allows for injecting values like authorization headers and base URLs into fetch requests, making it easier to manage API calls in your application.
Installation
Install the package using npm or yarn:
npm install @revas-hq/kit-fetch
# or
yarn add @revas-hq/kit-fetch
Usage
Creating a Context-Aware Fetch Function
import { createBaseUrlFetch, createContextFetch } from "@revas-hq/kit-fetch";
import type { Context } from "@revas-hq/kit-context";
const context: Context = {}; // Mock or create a context if needed
const baseApiUrl = "https://api.example.com/";
const fetchWithMiddlewares = createContextFetch(createBaseUrlFetch(baseApiUrl))(
context,
);
fetchWithMiddlewares("endpoint")
.then((response) => console.log(response))
.catch((error) => console.error(error));
Types and Interfaces
FetchMiddleware
A type for middleware that wraps the fetch function.
export type FetchMiddleware = (next: typeof fetch) => typeof fetch;
ContextFetchMiddleware;
A type for context-aware fetch middleware.
export type ContextFetchMiddleware = (context: Context) => FetchMiddleware;
ContextFetchFunction;
A type for creating a fetch function based on context.
export type ContextFetchFunction = (context: Context) => typeof fetch;
Functions
createBaseUrlFetch
Creates a middleware that adds a base URL to the request. Ensures the base URL ends with a slash.
export const createBaseUrlFetch: (baseUrl: string) => ContextFetchMiddleware;
createContextFetch
Creates a context-aware fetch function from a list of middleware factories.
export const createContextFetch: (
...factories: ContextFetchMiddleware[]
) => ContextFetchFunction;
License
This project is licensed under the MIT License. See the LICENSE file for details.