Skip to content

Commit

Permalink
feat(fsnetwork): Add option for interceptor (#808)
Browse files Browse the repository at this point in the history
Adds the option to specify interceptor functions, mostly for error logging:
https://www.npmjs.com/package/axios#interceptors
  • Loading branch information
Cauldrath authored and bweissbart committed Sep 23, 2019
1 parent fb098b0 commit 4c12c24
Showing 1 changed file with 35 additions and 3 deletions.
38 changes: 35 additions & 3 deletions packages/fsnetwork/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,12 @@ export type FSNetworkError = AxiosError;
*
* @see https://github.com/axios/axios#request-config
*/
export type FSNetworkRequestConfig = AxiosRequestConfig;
export interface FSNetworkRequestConfig extends AxiosRequestConfig {
// Function that is called to intercept any responses
responseIntercept?: (response: AxiosResponse) => AxiosResponse;
// Function that is called to intercept any response errors
responseError?: (error: any) => any;
}

/**
* A promise of a response from the network.
Expand Down Expand Up @@ -54,15 +59,42 @@ export type FSNetworkRequestData =
*/
export default class FSNetwork {
private instance: AxiosInstance;
private interceptor?: number;

/**
* Creates a new instance of FSNetwork.
*
* @param {FSNetworkRequestConfig} config Default configuration to apply to every request.
*/
constructor(config?: FSNetworkRequestConfig) {
this.instance = axios.create(config);
// TODO: intercept the request or response for logging
if (config) {
const {
responseIntercept,
responseError,
...axiosConfig
} = config;
this.instance = axios.create(axiosConfig);
this.setInterceptor(config);
} else {
this.instance = axios.create();
}
}

removeInterceptor(): void {
if (this.interceptor !== undefined) {
this.instance.interceptors.response.eject(this.interceptor);
this.interceptor = undefined;
}
}

setInterceptor(config?: FSNetworkRequestConfig): void {
this.removeInterceptor();
if (config && (config.responseIntercept || config.responseError)) {
this.interceptor = this.instance.interceptors.response.use(
config.responseIntercept,
config.responseError
);
}
}

/**
Expand Down

0 comments on commit 4c12c24

Please sign in to comment.