import axios, { AxiosError, AxiosRequestConfig } from 'axios' import { of } from 'await-of' import { Tokens, getClientOptions, ClientType } from './types' import { basePathForClient, verifyTokenValidity, clientDefaults, standaloneAxios } from './utils' import EntityManagerClient from '@rlvt/entity-manager-openapi-client' const createAxiosClient = (options: getClientOptions) => { // store current tokens used by this client const currentTokens: Partial = { refreshToken: options.authenticationType?.type === 'refresh_token' ? options.authenticationType.refreshToken : undefined } const entityManagerClient = new EntityManagerClient({ baseURL: `${options.gatewayEndpoint}/v2` }) // create specific axios instance for this client const axiosInstance = axios.create({ baseURL: `${options.gatewayEndpoint}${basePathForClient[options.type]}` }) axiosInstance.interceptors.request.use((config: AxiosRequestConfig) => { config.headers = Object.assign(config.headers ?? {}, { 'Content-Type': 'application/json', 'Authorization': `Bearer ${currentTokens.accessToken}` }) return config }) axiosInstance.interceptors.response.use(undefined, async (error: AxiosError) => { if (error.response?.status === 401) { const [ tokens, renewTokenError ] = await of(options.onAuthenticationRequired({ currentTokens, options, request: error.config!, client: entityManagerClient })) if (tokens === undefined) { options.onAuthenticationFailure(renewTokenError ?? new Error('authentication_failure')) return error.response } const [ profileResponse, profileError ] = await of(verifyTokenValidity(entityManagerClient, options.clientId, tokens)) if (profileResponse === undefined) { options.onAuthenticationFailure(profileError ?? new Error('authentication_failure')) return error.response } options.onAuthenticationSuccess(profileResponse.data.data.user) currentTokens.accessToken = tokens.accessToken currentTokens.refreshToken = tokens.refreshToken // re-launch the request with another axios instance to avoid recursive errors error.config!.headers = Object.assign(error.config?.headers ?? {}, { Authorization: `Bearer ${tokens.accessToken}`}) return standaloneAxios(error.config!) } throw error }) return axiosInstance } export * from './types' export const createClient = (_options: Partial & { type: ClientType, clientId: string }) => { const options = Object.assign(clientDefaults, _options) as getClientOptions return createAxiosClient(options) }