import type { AxiosError, AxiosResponse, CreateAxiosDefaults } from 'axios'; import axios from 'axios'; import type { ThreekitAuthProps } from './ThreekitAuthProps.js'; export const getAuthToken = (auth: ThreekitAuthProps) => { if ('publicToken' in auth) { return auth.publicToken; } if ('privateToken' in auth) { return auth.privateToken; } if ('cookie' in auth) { return auth.cookie; } throw new Error('No auth token found'); }; export const createThreekitAxios = (auth: ThreekitAuthProps) => { // yes, this is redundant if TypeScript is accurate, but I've seen people mess this up. --Ben, 2024-10-15 if (auth.host === undefined) { throw new Error('ThreekitAuthProps host is required'); } if (auth.orgId === undefined) { throw new Error('ThreekitAuthProps orgId is required'); } if (!('publicToken' in auth || 'privateToken' in auth || 'cookie' in auth)) { throw new Error( 'ThreekitAuthProps publicToken, privateToken, or cookie is required' ); } if (auth.host.includes('http://') || auth.host.includes('https://')) { throw new Error( 'ThreekitAuthProps host should not include http:// or https://' ); } const axiosDefaults: CreateAxiosDefaults = { baseURL: `https://${auth.host}`, ...('privateToken' in auth ? { params: { bearer_token: auth.privateToken } } : undefined), ...('cookie' in auth ? { headers: { Cookie: auth.cookie }, params: { orgId: auth.orgId } } : undefined), ...('publicToken' in auth ? { params: { bearer_token: auth.publicToken } } : undefined) }; const threekitAxios = axios.create(axiosDefaults); threekitAxios.interceptors.response.use( (response: AxiosResponse) => response, (error: AxiosError) => error.response ); return threekitAxios; };