All files / lib/apis/core index.ts

52.17% Statements 12/23
0% Branches 0/4
0% Functions 0/1
52.17% Lines 12/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63              1x         1x   1x   1x   1x 1x                                                     1x   1x         1x           1x 1x 1x  
import { APP_ENV, getLoginUrl } from '@lib/config';
import { Configuration, GameStateApi } from '@uniquegood/realworld-core-interface';
import axios from 'axios';
import { setLocalStorage } from '@lib/utils/localStorage';
import { memoizedApiAuthReissueGet } from '@lib/apis/auth/apiAuthReissueGet';
import { mobileInterceptRequest } from '@lib/apis';
 
const CORE_SERVER_HOST = {
  development: 'api-test.realworld.to',
  production: 'api.realworld.to'
}[APP_ENV];
 
const configuration = new Configuration({ basePath: `https://${CORE_SERVER_HOST}` });
 
const defaultAxiosInstance = axios.create({ baseURL: `https://${CORE_SERVER_HOST}` });
 
const tokenRefreshAxiosInstance = axios.create({ baseURL: `https://${CORE_SERVER_HOST}` });
 
const mobileTokenRefreshAxiosInstance = axios.create({ baseURL: `https://${CORE_SERVER_HOST}` });
tokenRefreshAxiosInstance.interceptors.request.use(async (config) => {
  let token: string | undefined;
 
  try {
    const {
      data: { token: newAccessToken, refreshToken: newRefreshToken }
    } = await memoizedApiAuthReissueGet();
 
    if (newAccessToken && newRefreshToken) {
      setLocalStorage('accessToken', newAccessToken);
      setLocalStorage('refreshToken', newRefreshToken);
    } else {
      throw new Error('No token or refreshToken');
    }
 
    token = newAccessToken;
  } catch (e) {
    alert('리얼월드 로그인이 필요한 콘텐츠입니다. 로그인 페이지로 이동합니다.');
 
    window.location.href = getLoginUrl(window.location.href);
  }
 
  config.headers.Authorization = `Bearer ${token}`;
 
  return config;
});
 
mobileTokenRefreshAxiosInstance.interceptors.request.use(mobileInterceptRequest);
 
export const gameStateWithTokenApi = new GameStateApi(
  configuration,
  undefined,
  tokenRefreshAxiosInstance
);
export const gameStateForWebviewApi = new GameStateApi(
  configuration,
  undefined,
  mobileTokenRefreshAxiosInstance
);
 
export const coreDirectApi = defaultAxiosInstance;
export const coreDirectWithTokenApi = tokenRefreshAxiosInstance;
export const coreDirectForWebviewApi = mobileTokenRefreshAxiosInstance;