0.5.16 ā€¢ Published 5 months ago

@anupamtest/fetch-api-interceptor v0.5.16

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

Simple Fetch API Interceptor

DEPRECATED: USE THIS INSTEAD @simbeto/fetch-api-interceptor


Native Fetch API doesn't facilitate Interceptors and calling relative urls.

This library allows to add multiple Interceptors for both Request & Response when using the native fetch api in the browser and NodeJs and facilitates to call relative urls after specifying baseUrl in its settings.

You may though combine code of multiple interceptors into one function and just add that one.

There is an example using all the features in the repo.

šŸ“„ Installation

npm i @anupamtest/fetch-api-interceptor
or
pnpm i @anupamtest/fetch-api-interceptor
or
yarn add @anupamtest/fetch-api-interceptor

šŸ“‘ How to Use

Import the library and define your Interceptor functions

  1. Import the Library
  2. Define your Interceptor functions
  3. Add your Interceptor functions
  4. Make your Fetch API requests

šŸŸ” Write the code of adding the Interceptors in some script in your application which is called only once.

import http from '@anupamtest/fetch-api-interceptor'

http.interceptors.request.add(yourRequestInterceptor_Function)
http.interceptors.response.add(yourResponseInterceptor_Function)

šŸ“„ Example

Lets take an example of getting some data from dummyjson.com and modify the request using the Request Interceptor

// app-init.ts
import http from '@anupamtest/fetch-api-interceptor'
import requestInterceptor_DummyJson from './my-interceptors.ts'

http.interceptors.request.add(requestInterceptor_DummyJson)


// my-interceptors.ts
export function requestInterceptor_DummyJson(url: string, config: RequestConfig): RequestFnResult {
    return new Promise((resolve) => {
        const u = new URL(url)

        if (u.hostname.startsWith('dummyjson')) {
            // get only 2 records
            setQueryLimit(u)

            // switch url path params to get something entirely different
            switchRequestPaths(u)
        }

        // After all changes done, set the full url
        url = u.href

        return resolve({ url, config })
    })
}


function setQueryLimit(u: URL) {
    u.searchParams.set('limit', '2')
}

function switchRequestPaths(u: URL) {
    if (u.pathname.startsWith('/products'))
        u.pathname = '/posts'

    else if (u.pathname.startsWith('/posts'))
        u.pathname = '/quotes'

    else if (u.pathname.startsWith('/quotes'))
        u.pathname = '/products'
}

That's basically it!

Now make your fetch api calls, as below.

const list = await http.get('https://dummyjson.com/quotes')
//
<pre> { list.data } </pre>

šŸ“„ Request Interceptors

Each Request Interceptor gets these parameters and must return them in a Promise after processing them.

PropDescription
urlThe url of the request
configThe Request config

šŸ“„ Response Interceptors

Each Response Interceptor gets data, response & request config and must return data in a Promise.

PropDescription
dataThe response data after processing it. Each Interceptor gets the data returned by its previous Interceptor. The first one get the original response data.

šŸ“„ The Final Response

All requests returns a Promise with the response data and the original response object. In the below example list.data will contain the response data after being handled by all the Response Interceptors.

PropDescription
dataResponse data after processed by all the Response Interceptors.
responseThe original response object returned by the server
const list = await http.get('https://dummyjson.com/products')
// => Promise<{ data: any, response: Response }>
//
<pre> { list.data } </pre>

šŸ“„ Interceptor Methods

MethodsDescription
getGets the list of interceptors added
addAdd interceptor
clearRemove all existing interceptors
// See the list of added interceptors
console.log(http.interceptors.request.get())
console.log(http.interceptors.response.get())

šŸ“„ Default Options

MethodsDescription
configGetter and Setter for the default request config
settingsGetter and Setter for default options for this library. These can also be set separately for individual requests.
- responseType <string: 'json' \| 'text' \| 'blob'>: The response data return format. Default is 'json'
- debug <boolean> : When true will log output to console.
- baseUrl <string> : Base Url to be prefixed to all requests.
- prefixBaseUrl <boolean> : When true will automatically set the base url to all requests which has a relative url. If the baseUrl is not set, current location's origin will be used as base url.
// get the list of default request config and settings.
console.log(http.config);
console.log(http.settings);
// set the default request config to be used by all requests
http.config = {
    authorization: 'Bearer uYXV0aDAuY29tLyIsImF1ZCI6Imh0dHB',
    // ...
}

// set the default base url and response data format to return by all requests
http.settings = {
    responseType: 'blob',
    debug: true,
    baseUrl: 'http://your-app-base-url.com',
    prefixBaseUrl: true;
}

// Now the default response data type will be of 'blob' type
// Base Url will be prefixed to the request
const res = await http.get('/quotes')

// blob data
console.log(await res.data.type) // application/json
const list = JSON.parse(await res.data.text()) // parse json string
// 
<pre> { JSON.stringify(list.data, null, 2) } </pre>
0.5.16

5 months ago

0.5.14

5 months ago

0.5.15

5 months ago

0.5.13

5 months ago

0.5.10

5 months ago

0.5.11

5 months ago

0.5.12

5 months ago

0.5.8

5 months ago

0.5.7

5 months ago

0.5.9

5 months ago

0.5.6

5 months ago

0.5.5

5 months ago

0.5.4

5 months ago

0.5.3

5 months ago

0.5.2

5 months ago