@andremalveira/axios v0.1.1
Axios Config Helper
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 isaxios 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, anUnauthorized
error is returned.
API Cookie
Used to treat the token in the cookie, it has the
set
,get
andremove
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:
name
: default:_token
options
: extends fromCookieAttributes
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 { createAxiosApi } from '@andremalveira/axios';
import routes from 'routes/api.routes';
const api = createAxiosApi<{ route: typeof routes }>({ // or endpoint: typeof endpoints
⠀⠀⠀baseURL: 'https://api',
⠀⠀⠀route: routes,
})