2.2.1 • Published 1 year ago

@distributedlab/json-api-client v2.2.1

Weekly downloads
-
License
MIT
Repository
-
Last release
1 year ago

@distributedlab/json-api-client

JSON API client

version (scoped package) types tree-shaking checks

This package moved to the new repository and not be maintained anymore.

Usage

Bearer token

// interceptors.ts
import { HTTPS_STATUS_CODES } from '@distributedlab/json-api-client'
import { AxiosInstance, AxiosRequestConfig } from 'axios'
import { useAuthStore } from '@/store'
import { router } from '@/router'
import { Bus } from '@/utils'
import { ROUTE_NAMES } from '@/enums'
import { useI18n } from '@/localization'

export function attachBearerInjector(axios: AxiosInstance): void {
  axios.interceptors.request.use((request): AxiosRequestConfig => {
    // Some authentication store in the client app
    const authStore = useAuthStore()
    if (!authStore.accessToken) return request

    if (!request.headers) request.headers = {}
    // Attach bearer token to every request
    request.headers['Authorization'] = `Bearer ${authStore.accessToken}`
    return request
  })
}

export function attachStaleTokenHandler(axios: AxiosInstance): void {
  axios.interceptors.response.use(
    response => response,
    async error => {
      const config = error?.config
      const isUnauthorized = (
        error?.response?.status === HTTPS_STATUS_CODES.UNAUTHORIZED &&
        !config?._retry
      )

      // If error isn't unauthorized or request was already retried - return error
      if (!isUnauthorized) return Promise.reject(error)

      // Some authentication store in the client app
      const authStore = useAuthStore()
      const { $t } = useI18n()

      try {
        config._retry = true
        // Executes some refresh token logic in the client app
        await authStore.refreshToken()

        // Reset default axios authorization header witn new token
        axios.defaults.headers.common['Authorization'] = `Bearer ${authStore.accessToken}`

        return axios(config)
      } catch (_error) {

        /** Example of handling refresh token error in the client app
         *
         * Implementation may differ from example
         *
         * We can logout user and redirect him to the login page and
         * emit bus error event to show user that session expired
        */
        authStore.logout()
        router.push({ name: ROUTE_NAMES.login })
        Bus.error({
          title: $t('api-errors.session-expired-title'),
          message: $t('api-errors.session-expired-desc'),
        })
        return Promise.reject(_error)
      }
    },
  )
}

// api.ts
import { JsonApiClient } from '@distributedlab/json-api-client';
import { attachBearerInjector, attachStaleTokenHandler } from '@/interceptors';

const axiosInstance = axios.create()
attachBearerInjector(axiosInstance)
attachStaleTokenHandler(axiosInstance)

export const api = new JsonApiClient({
  baseUrl: 'https://api.example.com',
  axios: axiosInstance,
});

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

2.2.1

1 year ago

2.2.0

1 year ago

2.1.1

1 year ago

2.1.0

1 year ago

2.0.3

2 years ago

2.0.2

2 years ago

2.0.4

2 years ago

2.0.1

2 years ago

2.0.0

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago