Socket
Book a DemoInstallSign in
Socket

@distributedlab/json-api-client

Package Overview
Dependencies
Maintainers
3
Versions
12
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@distributedlab/json-api-client

API Client for JSON API

2.2.1
latest
npmnpm
Version published
Weekly downloads
1
-75%
Maintainers
3
Weekly downloads
 
Created
Source

@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

FAQs

Package last updated on 06 Mar 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

About

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.

  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc

U.S. Patent No. 12,346,443 & 12,314,394. Other pending.