axiosでAPIをコールして認証切れだった場合、トークンを再取得してからリクエストをリトライする(リトライ回数上限付き)

const axiosConfig = {
  baseURL: baseUrl,
  retries: 1, // リトライ回数
  retryCount: 0,
}

const client = axios.create(axiosConfig)

// レスポンス時の処理
client.interceptors.response.use(
  response => {
    return response
  },
  async error => {
    if (error.response?.status === 401) {
      // 認証切れ
      if ((error.config.retries ?? 0) > (error.config.retryCount ?? 0)) {
        // リトライ回数が上限に達してない場合
        // リトライ回数を更新
        error.config.retryCount = (error.config.retryCount ?? 0) + 1
        // トークンを再発行
        const res = await client.post('/auth/v1/refresh', {
          username: xxxx,
        })
        // error.configからリクエスト情報を取り出す
        const config = error.config
        // config.headersは未定義になる可能性があるバグがあるため、暫定でJSON.parse
        config.headers = JSON.parse(
          JSON.stringify(config.headers || {})
        ) as RawAxiosRequestHeaders
        // トークンをヘッダーにつける
        config.headers['Authorization'] = `Bearer ${res.token}`
        // 元々のリクエストを再送信
        return client.request(config)
      }
    }
    return Promise.reject(error)
  }
)