Skip to content

Instantly share code, notes, and snippets.

@baruchvlz
Created February 8, 2019 13:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baruchvlz/a4fad3030fb5ea5ae4912271b09f7143 to your computer and use it in GitHub Desktop.
Save baruchvlz/a4fad3030fb5ea5ae4912271b09f7143 to your computer and use it in GitHub Desktop.
basic interceptor for fetch. assumes your routes are proxy through `/api-`
interface Interceptors {
request: { [k: string]: (...args: any[]) => any };
response: { [k: string]: (response: Response) => any };
}
class Interceptor {
protected requestCount: number = 0;
protected interceptors: Interceptors = {
request: {},
response: {},
};
private runInterceptors(type: keyof Interceptors, args: any | Response) {
const typeInterceptors = this.interceptors[type];
if (!typeInterceptors) {
return;
}
const keys = Object.keys(typeInterceptors);
keys.forEach((key: string) => {
typeInterceptors[key](args);
});
}
public registerInterceptor(name: string, type: keyof Interceptors, fn: any) {
if (!this.interceptors[type][name]) {
this.interceptors[type][name] = fn;
}
}
public init() {
const { fetch } = window;
window.fetch = (...args: any[]) => {
const url = args[0];
/**
* @note we can assume that all client side requests will be done with a /api proxy
* only requests that will not have this are GQL requests. should change this to run through
* /api-graphql
*/
const apiRx = /\/api-(.*)/;
if (url.match(apiRx)) {
this.runInterceptors('request', args);
}
return fetch.apply(window, args).then((response: Response) => {
if (url.match(apiRx)) {
this.runInterceptors('response', response);
}
return response;
});
};
}
}
export default new Interceptor();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment