@privyid/nuapi
NuAPI
Nuxt HTTP Client module
Features
- ✅ Using Fetch instead of XHR
- ✅ Built-in adapter for Retry, Dedupe, and Priority Queue request.
- ✅ Composable hook for Axios interceptors.
Compabilities
- Nuxt 3
Quick Setup
- Add
@privyid/nuapidependency to your project
yarn add --dev @privyid/nuapi
- Add
@privyid/nuapito themodulessection ofnuxt.config.ts
export default defineNuxtConfig({
modules: [
'@privyid/nuapi'
]
})
That's it! You can now use NuAPI in your Nuxt app ✨
Usage
import {
createLazyton,
ApiResponse,
AxiosRequestConfig
} from '@privyid/nuapi'
const useApi = createLazyton({ prefixURL: '/api' })
interface User {
userId: string,
email: string,
name: string
role: string,
}
interface FormUser {
name: string,
email: string,
role: string,
}
function getUserProfile (config?: AxiosRequestConfig): ApiResponse<User> {
return useApi().get('/user/profile', config)
}
function postUserProfile (body: FormUser, config?: AxiosRequestConfig): ApiResponse<User> {
return useApi().post('/user/profile', body, config)
}
Hook
There are available hook for add request/response interceptors.
import {
onRequest,
onRequestError,
onResponse,
onResponseError,
onError,
getCode,
getMessage,
} from '@privyid/nuapi/core'
function isUnauthorize (error: Error): boolean {
const code = getCode(error)
const message = getMessage(error)
return code === 401 && message.includes('Unauthorized')
}
/** set additional or custom headers */
onRequest((config) => {
const token: string = cookies.get('session/token') || ''
// check available authorization header
// and set authorization header
if (config.headers && !config.headers.Authorization && token)
config.headers.Authorization = `Bearer ${token}`
return config
})
/**
* check unauthorize error response
* cause of invalid or expired token
*/
onResponseError(async (error) => {
if (isUnauthorize(error)) {
await navigateTo('/login')
}
throw error
})
Queue
All request per instance will be add into queue before sent with priority MEDIUM (20).
If you want to send your request first before the others, you can set using option priority. The higher priority will run first.
import { QueuePriority } from '@privyid/nuapi/core'
useApi().get('/document/load', {
// Using presets
priority: QueuePriority.HIGH,
// Or using number
priority: 50,
})
Dedupe
Sometime, you want to cancel request with same endpoint like when you working with searching or filter.
NuAPI has built in function for this case. Just set requestkey, multiple sent request with same id will cancel last request before.
useApi().get('/document/load', {
requestkey: 'document-load',
})
Cancel Manually
Cancel spesific request by requestKey using .cancel()
useApi().cancel('document-load')
Or cancel all requests that have requestKey using .cancelAll()
useApi().cancelAll()
Retry
NuAPI automatically retries request when got an error with status code:
- 408 - Request Timeout
- 409 - Conflict
- 425 - Too Early
- 429 - Too Many Requests
- 500 - Internal Server Error
- 502 - Bad Gateway
- 503 - Service Unavailable
- 504 - Gateway Timeout
By default will retries 3 times (except for PATCH, POST, PUT, DELETE) can be changed using option retry.
useApi().get('/document/load', {
retry: 5,
})
Customize Retry Condition
You can customize when request should retries using retryOn
useApi().get('/document/load', {
retryOn (error) {
return getCode(error) === 423
&& error.config.retryCount < 3
},
})
API
👉 You can learn more about usage in JSDocs Documentation.
Contribution
- Clone this repository
- Play Nyan Cat in the background (really important!)
- Enable Corepack using
corepack enable(usenpm i -g corepackfor Node.js < 16.10) - Run
yarn install - Run
yarn dev:prepareto generate type stubs. - Use
yarn devto start playground in development mode.
License
MIT License
Related Packages
Version History
| Version | Released | Vue | License |
|---|---|---|---|
| 1.0.0 | ^3.0 | MIT | |
| 0.2.1 | ^3.0 | MIT | |
| 0.2.0 | ^3.0 | MIT | |
| 0.1.0 | ^3.0 | MIT |
Pre-releases (6)
| Version | Released | Vue | License |
|---|---|---|---|
| 0.3.0-alpha.6 | ^3.0 | MIT | |
| 0.3.0-alpha.5 | ^3.0 | MIT | |
| 0.3.0-alpha.4 | ^3.0 | MIT | |
| 0.3.0-alpha.3 | ^3.0 | MIT | |
| 0.3.0-alpha.2 | ^3.0 | MIT | |
| 0.3.0-alpha.1 | ^3.0 | MIT |