npm.io
2.2.1 • Published 3 years ago

@distributedlab/json-api-client

Licence
MIT
Version
2.2.1
Deps
5
Size
731 kB
Vulns
0
Weekly
0
DeprecatedThis package is deprecated

@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

Change

  • Deprecate package
2.2.0

Added

  • Meta typing in response
2.1.1

Fixed

  • Exporting JsonApiBodyBuilder from package
2.1.0

Added

  • Util that helps to create the body for POST requests
2.0.4

Removed

  • Axios paramsSerializer encode config
2.0.3

Changed

  • Updated axios to 1.0.0
2.0.2

Added

  • Export helpers, enums and types
2.0.1

Fixed

  • Build content in NPM package
2.0.0

Added

  • Ability to provide axios instance to make possible to inject interceptors from client code to handle authorization and refresh token logic

Removed

  • Ability to provide auth token
1.0.2

Fixed

  • @babel/runtime dependency
1.0.1

Fixed

  • Readme
1.0.0

Under the hood changes

  • Initiated project