All files / src/services api.ts

96.15% Statements 25/26
94.44% Branches 17/18
66.66% Functions 2/3
96.15% Lines 25/26

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      87x                     87x 143x 143x   143x 9x       143x 60x     143x       87x         20x 18x         18x 18x 15x       2x 1x   2x       3x 2x 2x 2x 1x 1x       4x          
import axios from 'axios'
import { useAuthStore } from '@/stores/auth'
 
const api = axios.create({
  baseURL: import.meta.env.VITE_API_URL || 'https://api.flows.browsway.com',
  headers: {
    'Content-Type': 'application/json'
  }
})
 
// Add the auth token and the tab's active flow to every request: the flow is
// the one of the tab's URL (/flows/:slug/...), not stored on the user, so the
// API acts on the flow this tab shows even while another tab works in another
// (see flows-api shared/activeFlow.js)
api.interceptors.request.use(async (config) => {
  const authStore = useAuthStore()
  const token = await authStore.getAccessToken()
 
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  // A caller naming a flow itself (e.g. the settings of a flow edited from the
  // Flows page, which may not be the tab's flow) keeps it
  if (authStore.currentFlow && !config.headers['X-Flow-Id']) {
    config.headers['X-Flow-Id'] = authStore.currentFlow
  }
 
  return config
})
 
// Handle auth errors
api.interceptors.response.use(
  (response) => {
    return response
  },
  async (error) => {
    if (error.response?.status === 401) {
      const authStore = useAuthStore()
      // Only logout if the session is truly expired (no valid token obtainable).
      // If getAccessToken() returns a token, the session is still valid: the
      // token may have expired between being read and being checked — force-
      // refresh it once and retry the request before giving up.
      const token = await authStore.getAccessToken()
      if (!token) {
        await authStore.logout()
        // A request still in flight after sign-out / account deletion lands here
        // once the SPA is already on /login: a hard reload would be redundant and
        // would interrupt any navigation in progress.
        if (window.location.pathname !== '/login') {
          window.location.href = '/login'
        }
        return Promise.reject(error)
      }
 
      // Session valid but 401: force-refresh the token once and retry.
      if (!error.config._retried) {
        error.config._retried = true
        const refreshedToken = await authStore.getAccessToken(true)
        if (refreshedToken) {
          error.config.headers['Authorization'] = `Bearer ${refreshedToken}`
          return api(error.config)
        }
      }
    }
    return Promise.reject(error)
  }
)
 
export default api