1.0.2 โ€ข Published 10 months ago

@alexfalconflores/safe-fetch v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months ago

๐Ÿš€ 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.)
  • AcceptType
  • CacheControlType
  • AcceptLanguageType
  • UserAgentType, 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

๐Ÿ“„ 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! ๐ŸŽ‰

1.0.2

10 months ago

1.0.1

10 months ago

1.0.0

10 months ago