1.0.2 โข Published 10 months ago
@alexfalconflores/safe-fetch v1.0.2
๐ Installation
npm install @alexfalconflores/safe-fetchโจ Features
- Auto-conversion from body to JSON if Content-Type: application/json is specified
- Strong typing for HTTP methods, headers and common network values
- Accepts extended and custom headers
- Supports standard fetch (can completely replace it)
๐ฆ Examples of use
โ๏ธ Basic Example
import safeFetch from "@alexfalconflores/safe-fetch";
const response = await safeFetch("/api/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer abc123",
},
body: { name: "Alex", email: "alex@correo.com" },
});
const data = await response.json();โ๏ธ Advanced Example
import safeFetch from "@alexfalconflores/safe-fetch";
const response = await safeFetch("/api/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: "Bearer 123token",
"Cache-Control": "no-cache",
},
body: { name: "Alex", email: "alex@correo.com" },
});
const data = await response.json();๐ฆ API
safeFetch(url: string, init?: RequestInitExt): Promise<Response>
url: Destination URL of the request.init: Optional object extending RequestInit, with typed headers.
๐งฉ Extended typing
RequestInitExt
interface RequestInitExt extends Omit<RequestInit, "headers"> {
method?: HttpMethod;
headers?: HeadersType;
}HttpMethod
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | ...;HeadersType
{
"Content-Type"?: ContentType;
Authorization?: AuthorizationType;
Accept?: AcceptType;
...
}Extendable types are included for:
AuthorizationType(Bearer, Basic, ApiKey, etc.)ContentType(application/json, text/html, etc.)AcceptTypeCacheControlTypeAcceptLanguageTypeUserAgentType, y muchos mรกs.
๐ ๏ธ Auxiliary function: Join
Join("-", "2025", "04", "19"); // "2025-04-19"๐งฉ Compatibility
Compatible with environments where fetch is available: modern browsers, Deno and Node.js (v18+ or with polyfill).
๐ค Autor
Alex Stefano Falcon Flores
- ๐ GitHub: alexstefano
- ๐ผ LinkedIn: alexsfalconflores
๐ License
This project is licensed under the MIT license. See the LICENSE file for more details.
โญ Do you like it?
Give the repo a star to support the project! And if you use it in your projects, I'd love to see it! ๐