A helper for configuring the client API service using axios
pnpm i @andremalveira/axios
// 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;
For requests that don't need authentication. The
public
method isaxios default mode
, no token checking is done.
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.
Used to treat the token in the cookie, it has the
set
,get
andremove
methods.
A helper for configuring the api's use of routes, see how to use api route.
// services/api.ts
import { createAxiosApi } from '@andremalveira/axios';
const api = createAxiosApi(); // createAxiosApi(config)
Config extends default axios configuration
CreateAxiosDefaults
.
baseURL
tokenAccessType
cookie
refreshToken
route or endpoint
Api base url
Authorization header access type
default:Bearer
Cookie settings
properties:
name
: default:_token
options
: extends fromCookieAttributes
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 ⠀⠀⠀} })
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)
// services/api.ts
import routes from 'routes/api.routes';
const api = createAxiosApi<{ route: typeof routes }>({
⠀⠀⠀baseURL: 'https://api',
⠀⠀⠀route: routes,
})