Created
December 30, 2022 15:38
-
-
Save julioflima/0c6b9513db772a933ef57e58e3db28e5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Turn public