Skip to content

Instantly share code, notes, and snippets.

@julioflima
Created December 30, 2022 15:38
Show Gist options
  • Save julioflima/0c6b9513db772a933ef57e58e3db28e5 to your computer and use it in GitHub Desktop.
Save julioflima/0c6b9513db772a933ef57e58e3db28e5 to your computer and use it in GitHub Desktop.
import axios, { AxiosRequestConfig } from 'axios';
import useAuth from 'hooks/useAuth';
const findOperationName = (gql: string) => {
const indexOfParentesis = gql.indexOf('(');
const indexOfSpaceNearParentesis = Array(...gql).reduce(
(acc, curr, index) => (curr === ' ' && indexOfParentesis - index > acc ? index : acc),
0
);
return gql.substring(indexOfSpaceNearParentesis + 1, indexOfParentesis);
};
const useAxios = () => {
const auth = useAuth();
const url = String(process.env.NEXT_PUBLIC_API_URL);
const buildHeaders = async () => {
const jwtToken = (await auth.currentSession()).getAccessToken().getJwtToken();
const impersonatedUserId = localStorage?.getItem('impersonatedUserId');
console.log('jwtToken', jwtToken);
return {
headers: {
...(jwtToken ? { Authorization: `Bearer ${jwtToken}` } : {}),
...(impersonatedUserId ? { 'X-Impersonated-User-Id': impersonatedUserId } : {})
}
};
};
const api = axios.create({
headers: {},
baseURL: url
});
api.interceptors.request.use(
async (config: AxiosRequestConfig<{ gql: string; variables?: object }>) => {
// Do something before request is sent
return {
...config,
...(await buildHeaders()),
method: 'post',
data: {
operationName: findOperationName(config?.data?.gql as string),
query: config?.data?.gql,
variables: config?.data?.variables
}
};
},
function (error) {
// Do something with request error
return Promise.reject(error);
}
);
//TODO: Add a response interceptor
api.interceptors.response.use(
function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
},
function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
}
);
return api;
};
export default useAxios;
@julioflima
Copy link
Author

Turn public

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment