GithubHelp home page GithubHelp logo

marekdev-me / tailorfetch Goto Github PK

View Code? Open in Web Editor NEW
2.0 1.0 0.0 171 KB

TailorFetch is a lightweight Node.js library for making HTTP requests with customizable options and response transformations.

Home Page: https://www.npmjs.com/package/tailorfetch

TypeScript 100.00%
http-client npm-package

tailorfetch's Introduction

Node.js Package

TailorFetch

TailorFetch is a lightweight Node.js library for making HTTP requests with customizable options and response transformations.

Warning WIP! Documentation might be outdated or incomplete

Installation

npm install tailorfetch 

Features

  • Simplified HTTP GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS requests
  • Flexible options for headers, query parameters, timeouts, and more
  • Ability to transform response data using custom transformers
  • Ability to intercept request with custom intercept logic
  • Easy-to-use interface for handling common use cases
  • Enables use of Redis or built-in caching

Usage

Making GET Request

import TailorFetch from 'tailorfetch';

await TailorFetch.GET('https://dummyjson.com/products');

Making POST Request

import TailorFetch from 'tailorfetch';

const url = 'https://dummyjson.com/products/add';
const options = {
    body: JSON.stringify({
      title: 'BMW Pencil'
    }),
};

await TailorFetch.POST(url, options);

Supported Methods:

  • GET - Retrieves data or information from a specified resource.
  • POST - Submits data to be processed to a specified resource.
  • PUT - Updates a specified resource or creates it if it doesn't exist.
  • PATCH - Applies partial modifications to a resource.
  • DELETE - Deletes a specified resource.
  • HEAD - Requests headers from a specified resource without the actual data.
  • OPTIONS - Requests information about the communication options for a resource.

Options:

  • headers - An object containing request headers.
  • queryParams - An object containing query parameters for the URL.
  • timeout - The request timeout in milliseconds.
  • json - Set to true to parse the response as JSON.
  • body - Data to be sent to remote server
  • transformResponse - A custom response transformer.
  • requestInterceptor - A custom request interceptor
  • requestMode
  • requestCache
  • requestCredentials
  • onProgress - Callback function for progress reporting
  • cache:
    • expiresIn - How long should cache be valid for (milliseconds)
    • redisClient - Redis client instance
  • retry:
    • maxRetries - Maximum number of times to attempt to make an HTTP request
    • retryDelay - Number of milliseconds to wait between attempts

Cache

Built-in cache

Warning Built-in cache might be unstable and might return live results at all times

By default, when cache option is specified with only expiry time and no redis client option has been specified then internal cache will be used.

Redis Cache

You can use Redis cache with GET requests by supplying Redis client to request cache options as follows.

import TailorFetch, { TailorResponse } from 'tailorfetch';
import {createClient} from 'redis';

// Setup redis
const client = createClient();
client.on('error', (error) => console.log(error));
client.connect();

// Request options
const options = {
   cache: {
      expiresIn: 600000,
      redisClient: client
   }
};

await TailorFetch.GET('https://dummyjson.com/products/1', options);

Custom Request Interceptor

You can define a custom request transformer by extending the BaseRequestInterceptor class and overriding the intercept method. Modify headers, add authentication, or enhance the request before it's sent.

Class based interceptor:

import {BaseRequestInterceptor} from 'tailorfetch';

class MyInterceptor implements BaseRequestInterceptor {
   intercept(requestOptions: RequestInit) {
      // Custom intercept logic
      
      return requestOptions;
   }
}

const options = {
   requestInterceptor: new MyInterceptor(),
};

await TailorFetch.GET(url, options);

Function based interceptor:

import {IRequestOptions} from 'tailorfetch';

const options = {
   requestInterceptor: (requestOptions: RequestInit): RequestInit => {
       
       // Custom request interceptor logic
       return requestOptions;
   },
};

await TailorFetch.GET(url, options);

Custom Response Transformer

You can define a custom response transformer by extending the BaseTransform class and overriding the transform method.

Class based transformer:

import TailorFetch, {BaseTransform, IRequestOptions} from 'tailorfetch';

class MyTransformer implements BaseTransform {
   transform(responseData: any, requestOptions: IRequestOptions) {
      // Custom transformation logic
      return transformedData;
   }
}

const options = {
   transformResponse: new MyTransformer,
};

await TailorFetch.GET(url, options);

Function based transformer:

import TailorFetch, {BaseTransform, IRequestOptions} from 'tailorfetch';

const options = {
   transformResponse: (responseData: any, requestOptions: IRequestOptions): any => {
      // Custom transformation logic
      return transformedData;
   }
}

await TailorFetch.GET(url, options);

Helper Functions

TailorResponse

Following helper functions are available on TailorResponse returned when request is made

  • json() - Returns parsed JSON data, only if parseJSON request option is false
  • successful() - Returns boolean whether request was successful
  • failed() - Returns boolean whether request has failed
  • clientError() - Returns boolean whether an error was client error
  • serverError() - Returns boolean whether an error was server error

tailorfetch's People

Contributors

marekdev-me avatar snyk-bot avatar

Stargazers

 avatar  avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.