Skip to content

Interceptors

Axle provides practical request/response interceptors, compatible with both axle and axios.

Import

ts
import {
  requestHeadersInterceptor,
  requestMockInterceptor,
  requestMd5Interceptor,
  responseRetryInterceptor,
  responseStatusInterceptor,
  responseBlobInterceptor,
} from 'rattail/axle'

Usage with Axle

ts
axle.useRequestInterceptor(
  requestHeadersInterceptor({
    headers: () => ({
      token: localStorage.getItem('token'),
    }),
  }),
)

axle.useResponseInterceptor(responseRetryInterceptor({ count: 3 }))

Usage with Axios

ts
const {
  onFulfilled,
  onRejected,
  options,
} = responseRetryInterceptor({ count: 3 })

axios.interceptors.response.use(onFulfilled, onRejected, options)

General Parameters

All built-in interceptors accept these common options:

ParameterDescriptionType
includeOnly apply the interceptor to matching requestsFilterPattern[]
excludeSkip the interceptor for matching requestsFilterPattern[]
axiosInterceptorOptionsOptions passed to axios interceptor registrationobject

include & exclude

Each built-in interceptor supports include and exclude for request filtering. The following patterns are supported:

  • method:xxx — match by HTTP method (e.g. method:get, method:post)
  • Glob syntax — match by URL pattern (e.g. /user/**, /system/*)
  • status:xxx — match by response status code (e.g. status:500, status:401)
  • Function — custom matching logic (config) => boolean
ts
axle.useResponseInterceptor(
  responseRetryInterceptor({
    count: 3,
    include: ['method:put', 'method:post', 'status:500'],
    exclude: ['/system/**', '/user/addUser', 'status:400'],
  }),
)

Built-in Interceptor List

NameDescription
requestHeadersInterceptorCustomize request headers
requestMockInterceptorMock data
requestMd5InterceptorCompute MD5 hash for parameters and headers
responseRetryInterceptorRequest retry on failure
responseStatusInterceptorIntercept by status code
responseBlobInterceptorIntercept blob responses