@ronas-it/axios-api-client
TypeScript icon, indicating that this package has built-in type declarations

0.1.0 • Public • Published

axios-api-client

Wrapper utilities for interaction with REST APIs using Axios.

Getting started

  1. Install the package:
npm i @ronas-it/axios-api-client
  1. Create API service instance:
import { ApiService } from '@ronas-it/axios-api-client';
import { configuration } from './configuration';

export const apiService = new ApiService(configuration.apiURL);

Usage

import {
  ApiService,
  AuthConfiguration,
  RefreshTokenInterceptorOptions,
  tokenInterceptor,
  onResponseRefreshTokenInterceptor,
  onRequestRefreshTokenInterceptor,
} from '@ronas-it/axios-api-client';

const configuration: AuthConfiguration = {
  apiURL: 'https://api.your-app.dev',
  auth: {
    refreshTokenRoute: '/auth/refresh',
    unauthorizedRoutes: ['/auth/forgot-password', '/auth/restore-password'],
    logoutRoute: '/logout',
  },
};

const apiService = new ApiService(configuration.apiURL);

const options: RefreshTokenOptions = {
  configuration: configuration.auth,
  getIsAuthenticated: () => {
    /* get isAuthenticated state here */
  },
  runTokenRefreshRequest: async () => {
    const { token, ttl } = await apiService.get('/refresh');
    /* do something with token and ttl */

    return token;
  },
  onError: () => apiService.post('/logout'),
};

apiService.useInterceptors({
  request: [
    [
      tokenInterceptor({
        getToken: () => {
          /* get token here */
        },
      }),
    ],
  ],
});

apiService.useInterceptors({
  request: [[onRequestRefreshToken(options)]],
  response: [
    [null, onResponseRefreshToken(options)],
    [
      null,
      unauthorizedInterceptor({
        publicEndpoints: configuration.auth.unauthorizedRoutes,
        onError: () => apiService.post('/logout'),
      }),
    ],
  ],
});

Package Sidebar

Install

npm i @ronas-it/axios-api-client

Weekly Downloads

5

Version

0.1.0

License

MIT

Unpacked Size

54.3 kB

Total Files

9

Last publish

Collaborators

  • ipakhomov
  • eleonov
  • astorozhevsky
  • opikhnenko
  • dmitryusenko