All files / src/libs/axios index.ts

73.33% Statements 99/135
37.5% Branches 12/32
100% Functions 6/6
73.33% Lines 99/135

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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209  1x 1x 1x 1x 1x       1x   1x 1x 2x 2x 7x 7x 2x 2x 2x 7x 3x 5x 5x 5x 3x 7x 2x 2x 2x 2x   1x   1x 1x 1x   1x 1x 1x                   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                 1x 1x 1x 1x 1x 1x 1x 1x                 1x 1x 1x       1x 1x 1x 1x 1x     1x 1x     1x   1x   1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x               1x 1x       1x               1x 1x   1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x   1x 1x 1x                                                           1x         1x        
// region Dependency Injection
import axios, {type AxiosError, AxiosHeaders, type AxiosInstance, type InternalAxiosRequestConfig,} from 'axios'
import {auth} from '@/config/firebase'
import {useSchemaLogger} from '@/libs/logger/logger'
import {useAuthStore} from '@/stores/auth'
import {useLoadingStore} from '@/stores/loading'
// endregion Dependency Injection
 
// region constants
const httpLog = useSchemaLogger({ logger: 'axios' })
// ユーティリティ(簡易マスク & サイズ抑制)
const REDACT_KEYS = ['authorization', 'password', 'passwd', 'token', 'idToken', 'refreshToken']
const redact = (obj: any, max = 1024): any => {
  try {
    const json = JSON.stringify(obj, (_k, v) => {
      if (typeof v === 'string' && v.length > max) return v.slice(0, max) + '…'
      return v
    })
    const parsed = JSON.parse(json)
    const walk = (o: any) => {
      if (o && typeof o === 'object') {
        for (const k of Object.keys(o)) {
          if (REDACT_KEYS.includes(k.toLowerCase())) o[k] = '[REDACTED]'
          else walk(o[k])
        }
      }
    }
    walk(parsed)
    return parsed
  } catch { return { note: 'redact_failed' } }
}
 
const genReqId = () => (crypto?.randomUUID ? crypto.randomUUID() : `${Date.now()}-${Math.random()}`)
 
const LOADING_EXCLUDE: (string | RegExp)[] = [/\/healthz$/]
const shouldTrack = (url?: string) =>
  url ? !LOADING_EXCLUDE.some((p) => typeof p === 'string' ? url.includes(p) : p.test(url)) : true
 
const loadLocale = () => {
  return sessionStorage.getItem('lang') || localStorage.getItem('lang') || (navigator.language?.split('-')[0] ?? 'ja')
}
// endregion constants
 
// region props
// endregion props
 
// region variable
// endregion variable
 
// region properties
const base = import.meta.env.VITE_API_BASE_URL || ""; // ← ここが肝
const api: AxiosInstance = axios.create(
  {
    baseURL: base,
    withCredentials: true,
    timeout: import.meta.env.VITE_API_TIMEOUT,
    headers: {
      'Content-type': 'application/json',
    }
  }
)
 
// endregion properties
 
// region emits
// endregion emits
 
// region validator
// endregion validator
 
// region methods
/**
 * リクエスト共通処理
 *
 * todo : 認証周りの対応したときに追記する
 *        https://zenn.dev/rsi_dev/articles/dad6c6c25ed970
 */
api.interceptors.request.use(
    async (request : InternalAxiosRequestConfig) => {
      const s = useLoadingStore()
      if (shouldTrack(request.url)) {
        (request as any).__loadingToken = s.start('axios')
      }
      const user = auth.currentUser
      if (user) {
        try {
          const token = await user.getIdToken()
          request.headers.authorization = `Bearer ${token}`
        } catch (e) {
          console.warn('token取得失敗:', e)
        }
      }
      // ← {} を入れない。必ず AxiosHeaders に揃える
      const headers =
        request.headers instanceof AxiosHeaders
          ? request.headers
          : new AxiosHeaders(request.headers)
 
      // 既存があれば流用、なければ発番
      let reqId = headers.get('X-Request-Id') as string | null
      if (!reqId) {
        reqId = genReqId()
        headers.set('X-Request-Id', reqId)
      }
 
      // 言語定義
      const locale = loadLocale()
      headers.set("Accept-Language", locale)
 
      // 型安全に戻す(ここで型エラーが消える)
      request.headers = headers
 
      ;(request as any)._t0 = performance.now?.() ?? Date.now()
 
      httpLog.debug('HTTP request', {
        reqId,
        method: (request.method || 'get').toUpperCase(),
        url: (request.baseURL || '') + (request.url || ''),
        params: request.params ? redact(request.params) : undefined,
        hasData: !!request.data,
        data: request.data ? redact(request.data) : undefined,
      })
 
      const authStore = useAuthStore()
      const token = await authStore.refreshIdToken(false)
      if (!token) return request
 
      // 既存の headers が AxiosHeaders(v1のクラス)なら set() を使う
      if (headers instanceof AxiosHeaders) {
        headers.set('Authorization', `Bearer ${token}`)
      }
 
      return request
    },
    (error: AxiosError) => {
      console.error(`request error : ${JSON.stringify(error)}`)
      return Promise.reject(error)
    }
)
 
/**
 * レスポンス共通処理
 *
 * todo : 認証周りの対応したときに追記する
 *        https://zenn.dev/rsi_dev/articles/dad6c6c25ed970
 */
api.interceptors.response.use(
    (response) => {
      // console.log(`response: ${JSON.stringify(response)}`)
      const t0 = (response.config as any)._t0
      const ms = t0 ? Math.round((performance.now?.() ?? Date.now()) - t0) : undefined
      const reqId = (response.config.headers as any)?.['X-Request-ID']
 
      // 2xx/3xx は debug
      httpLog.debug('HTTP response', {
        reqId,
        status: response.status,
        method: (response.config.method || 'get').toUpperCase(),
        url: (response.config.baseURL || '') + (response.config.url || ''),
        ms,
        data: response.data ? redact(response.data) : undefined,
      })
 
      const s = useLoadingStore()
      const token: symbol | undefined = (response.config as any).__loadingToken
      if (token) s.stop(token)
 
      return response
    },
    async (error) => {
      // console.error(`error: ${JSON.stringify(error)}`)
      const cfg = error.config || {}
      const reqId = (cfg.headers as any)?.['X-Request-ID']
      const t0 = (cfg as any)._t0
      const ms = t0 ? Math.round((performance.now?.() ?? Date.now()) - t0) : undefined
 
      // ステータスに応じて warn/error(どちらでもサーバ送信対象)
      // console.error(`status : ${error.response?.status}`)
      const level = error.response?.status >= 500 ? 'error' : 'warn'
      const payload = {
        reqId,
        status: error.response?.status,
        code: error.code,
        method: (cfg.method || 'get').toUpperCase(),
        url: (cfg.baseURL || '') + (cfg.url || ''),
        ms,
        response: error.response?.data ? redact(error.response.data) : undefined,
        message: String(error.message || error),
      }
      // if (level === 'error') httpLog.error('HTTP error', payload)
      // else httpLog.warn('HTTP warn', payload)
      httpLog.warn(level, payload)
 
      const s = useLoadingStore()
      const token: symbol | undefined = (error?.config as any).__loadingToken
      if (token) s.stop(token)
 
      return Promise.reject(error)
    }
)
 
// endregion methods
 
// region export
export default api
 
// endregion export