Skip to content

Simone4e/FetcherJS

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 

Repository files navigation

📡 Fetcher JS Utility

A lightweight and flexible JavaScript class for making HTTP requests with support for:

  • FormData (including nested objects)
  • JSON payloads
  • Request timeouts
  • Centralized error handling
  • Automatic response parsing (json, text, blob)
  • Optional returnFullResponseOnError

🚀 Installation

Simply copy the Fetcher.js file into your project:

# Or clone the repository
git clone https://github.com/Simone4e/FetcherJS.git

Then import it:

import Fetcher from './Fetcher.js';

✨ Features

  • ✅ POST/GET with FormData or JSON
  • ✅ Automatic query string for GET requests
  • ✅ Timeout support via AbortController
  • ✅ Centralized HTTP error handling
  • ✅ Optional full response return on error
  • ✅ Lightweight and dependency-free

🛠️ Usage

Create an instance:

const fetcher = new Fetcher('/api/', {
  'Authorization': 'Bearer your-token'
});

Basic POST request:

await fetcher.request({
  method: 'POST',
  url: 'user/create',
  data: {
    name: 'Alice',
    email: '[email protected]'
  }
});

GET request with query parameters:

await fetcher.request({
  method: 'GET',
  url: 'user/list',
  data: { page: 1, search: 'john' }
});

Send JSON instead of FormData:

await fetcher.request({
  method: 'POST',
  url: 'auth/login',
  headers: {
    'Content-Type': 'application/json'
  },
  data: {
    email: '[email protected]',
    password: 'password'
  }
});

📦 API

new Fetcher(baseURL, defaultHeaders)

  • baseURL (string): Prefix added to all URLs.
  • defaultHeaders (object): Default headers for all requests.

request(config)

Option Type Description
methodstringHTTP method (default: 'POST')
urlstringEndpoint (appended to baseURL)
dataobjectData to send (FormData or JSON)
headersobjectAdditional headers
timeoutnumberRequest timeout in ms (default: 10000)
responseTypestring'json', 'text', or 'blob' (default: 'json')
returnFullResponseOnErrorbooleanIf true, returns { data, response } on error

Returns: Parsed response or full error response if returnFullResponseOnError is true.

handleHttpError(status, message)

Centralized error handler. You can customize behavior based on the HTTP status code.

  • 401: Not authenticated
  • 403: Authenticated but unauthorized
  • 422: Validation errors (shows alert)
  • Default: logs to console

static appendFormData(formData, data, parentKey = '')

Converts a nested object into a valid FormData instance.

const fd = new FormData();
Fetcher.appendFormData(fd, {
  user: {
    name: 'Mario',
    address: { city: 'Rome' }
  }
});

🧪 Example: Return full response on error

const result = await fetcher.request({
  method: 'POST',
  url: 'user/update',
  data: { name: 'Test' },
  responseType: 'json',
  returnFullResponseOnError: true
});

if (result.response && !result.response.ok) { console.error('Error:', result.data); } else { console.log('Success:', result); }


📄 License

MIT License © Rossaini Simone

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published