1.3.0 • Published 2 years ago

@default-js/defaultjs-httpinterceptor v1.3.0

Weekly downloads
1
License
MIT
Repository
github
Last release
2 years ago

defaultjs-httpinterceptor

Intro

This default-js modul provide functionality to intercept browser request and manipulate them. It's useful web pages with multi backend services on different domains or auhorization to provide the authorization to all requests.

The httpinterceptor works with XMLHttpRequest and fetch, but its supporting async requests only!

Install

npm

npm install @default-js/defaultjs-httpinterceptor
import {Manager} from "@default-js/defaultjs-httpinterceptor";
Manager.setup(async () => {
//setup your interceptor(s)
});

browser

<script type="application/javascript" src="/dist/defaultjs-httpinterceptor.min.js"></script>
<script type="application/javascript">

defaultjs.httpinterceptorManager.setup(async () => {
//setup your interceptor(s) -> see Javascript api
});
</script>

Include the javascript file and your setup script at head or as first script tags on your body!

Javascript API

Manager

This manager provides the main logic and optimized the request handling by caching the used interceptors by origin.

Manager.setup(setup)

Add your setup logic to the Manager instance and blocks all requests until all setup finished!

ParamRequiredDefaultDescription
setupXfunction or Promise object

The result of the setup can be a single object of Interceptor, an array of Interceptor objects or nothing, but then you must be add your Interceptor object(s) by calling Manager.addInterceptor manualy.

import {Manager} from "@default-js/defaultjs-httpinterceptor";
Manager.setup(async () => {
//setup your interceptor(s)
});

Manager.addInterceptor(interceptor)

Add a Interceptor object.

ParamRequiredDefaultDescription
interceptorXInterceptor or Array of Interceptor
Manager.addInterceptor(new MyInterceptor());
Manager.addInterceptor([new InterceptorA(), new InterceptorB(), new InterceptorC()]);

Every interceptor must be a instance of type Interceptor or an object with a function doAccept(data) and doHandle(data);

Manager.ready

This property is a Promise, that represented the current setup state.

Manager.ignoreDocumentOrigin

This property is tells the Manager to ignore all requests with the same origin as the current page.

Manager.addOriginToIgnore(origin)

Add origin to be ignored by Manager.

ParamRequiredDefaultDescription
originXstring, URL, Array

Manager.addUrlToIgnore(urls = [array of strings | array of URL | string | URL])

Add url to be ignored by Manager.

ParamRequiredDefaultDescription
urlXstring, URL, Array

Manager.uncheckedFetch(url, request)

This function make a unchecked fetch request. See default browser fetch api.

ParamRequiredDefaultDescription
urlXstring or URL
requestXobject or Request object

Manager.doIntercept(data)

This function would be called automaticly by fetch and XMLHttpRequest to intercept the requests.

ParamRequiredDefaultDescription
dataXobject

Manager.reset()

This function reset the interceptor-origin cache.

Interceptor

Basic class to extends by your own interceptor implementation.

Interceptor.doAccept({url, metadata})

This functions must be return true, if the interceptor apply to all requests by same origin.

ParamDefaultDescription
urlURL
metadataMetadata

@return: true or false

Interceptor.doHandle({url, metadata, request})

This function would be called to maipulate the request.

ParamDefaultDescription
urlURL
metadataMetadata
requestObject like fetch Request object

@return: a object of {url, metadata, request}

Interceptor.uncheckedFetch

This function make a unchecked fetch request. See default browser fetch api.

ParamRequiredDefaultDescription
urlXstring or URL
requestXobject or Request object

TokenInterceptor

The TokenInterceptor extends Interceptor and provide logic to cache a auth token and make periodicly a refesh of auth token.

import TokenInterceptor from "@default-js/defaultjs-httpinterceptor/src/interceptors/TokenInterceptor";
new TokenInterceptor(setup)

Structur of setup

PropertyRequieredDescription
conditionXstring, Array of string, function({url, metadata})
fetchTokenXfunction({url, metadata})
appendTokenfunction({url, metadata, request}); default: add token as header Authorization=Bearer ${token}
refreshIntervalnumber for milliseconds. A number zero or below -> disable automatic token refesh; default: 6000
refreshTokenfunction({url, metadata})

Object Metadata

This object provide some meta infomation of request.

PropertyRequiredDescription
methodXstring -> http verbs
originXorigin of request
hostnameXhostname of request
protocolXprotocol of request
port
queryXquery string of request

How to implemente a custom Interceptor

Create a new class and extend the class by Interceptor class. Impement the function doAccept(data) and doHandle(data).

import Manager from "@default-js/defaultjs-httpinterceptor";
import Interceptor from "@default-js/defaultjs-httpinterceptor";

class MyInterceptor extends Interceptor {
	#origin;

	constructor(origin){
		super();
		this.#origin = origin;
	}

	async doAccept({url, metadata}){
		return url.origin == this.#origin;
	}

	async doHandle({url, metadata, request}){
		const token = await this.uncheckedFetch("/url/to/token");
		request.headers["Authorization"] = `Bearer ${await token.text()}`;

		return {url, metadata, request};
	}
}

Manager.setup(async () => {
	const response = await Manager.uncheckedFetch("/request/for/all/origins.json");
	const origins = await response.json(); // response: ["example-a.com", "example-b.com", "example-c.com"]
	const interceptors = origins.map((origin) => new MyInterceptor(origin));

	return origins
});

await fetch("example-a.com");