Skip to content

andremalveira/axios

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Axios Config Helper

License-MIT  Version

A helper for configuring the client API service using axios

Table of contents

Install

pnpm i @andremalveira/axios

Quick start

// Login example

import api from '@andremalveira/axios';

const res = await api.public.post('{baseUrl}/login', { username, password });
const token = res.data.token;

api.cookie.set(token)
// Api route private

import api from '@andremalveira/axios';

const res = await api.private.post('{baseUrl}/user');
const data = res.data;

API Public

For requests that don't need authentication. The public method is axios default mode, no token checking is done.

API Private

For requests that need to send authentication token. The private method, by default, has interceptors configured to check if there is a token in the cookie and passes this token in the authorization header, if it does not exist, an Unauthorized error is returned.

API Cookie

Used to treat the token in the cookie, it has the set, get and remove methods.

API Route

A helper for configuring the api's use of routes, see how to use api route.

Create Axios Api

// services/api.ts

import { createAxiosApi } from '@andremalveira/axios';

const api = createAxiosApi(); // createAxiosApi(config)

Configurations

Config extends default axios configuration CreateAxiosDefaults.

baseURL
tokenAccessType
cookie
refreshToken
route or endpoint

baseUrl

Api base url

tokenAccessType

Authorization header access type
default: Bearer

cookie

Cookie settings
properties:

refreshToken

Receives a promise function that returns the updated token.

  • param: token
  • return: token - required
// services/api.ts

import { createAxiosApi } from '@andremalveira/axios';

const api = createAxiosApi({
⠀⠀⠀baseURL: 'https://api',    
⠀⠀⠀refreshToken: async (token) => {
⠀⠀⠀⠀⠀const res = await api.public.post('/refreshtoken', { token });
⠀⠀⠀⠀⠀const newToken = res.data.token as string
⠀⠀⠀⠀⠀return newToken
⠀⠀⠀}
})

Route

A helper for configuring the api's use of routes

⭐ See about Helpers for creating API route paths to the client.

// routes/api.routes.ts

const routes = {
    login: '/auth/login',
    users: '/users'
}
export default routes
// services/api.ts

import { createAxiosApi } from '@andremalveira/axios';
import routes from 'routes/api.routes';

const api = createAxiosApi({
⠀⠀⠀baseURL: 'https://api',
⠀⠀⠀route: routes, // or endpoint: routes
})
// Example of use

const res = await api.public.post(api.route.login)

Using typescript for route type

// services/api.ts

import routes from 'routes/api.routes';

const api = createAxiosApi<{ route: typeof routes }>({
⠀⠀⠀baseURL: 'https://api',
⠀⠀⠀route: routes,
})

using-typescript-for-route-type.png

Related / Dependencies

axios
js-cookie

Licence

MIT