npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@simbeto/fetch-api-interceptor

v1.0.1

Published

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

Downloads

2

Readme

Simple 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.

| Prop | Description | | ---- | ----------- | | url | The url of the request | config | The Request config

📄 Response Interceptors

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

| Prop | Description | | ---- | ----------- | | data | The 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.

| Prop | Description | | ---- | ----------- | | data | Response data after processed by all the Response Interceptors. | response | The 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

| Methods | Description | | ------- | ----------- | | get | Gets the list of interceptors added | add | Add interceptor | clear | Remove all existing interceptors


// See the list of added interceptors
console.log(http.interceptors.request.get())
console.log(http.interceptors.response.get())

📄 Default Options

| Methods | Description | | ------- | ----------- | | config | Getter and Setter for the default request config | settings| Getter 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>