在 axios 封装的时候接受一个 mock 参数,然后根据 mock 参数对响应进行拦截
type GetConfig = Omit<AxiosRequestConfig, 'params' | 'url' | 'method'>
type PostConfig = Omit<AxiosRequestConfig, 'url' | 'data' | 'method'>
type PatchConfig = Omit<AxiosRequestConfig, 'url' | 'data'>
type DeleteConfig = Omit<AxiosRequestConfig, 'params'>
export class Http {
instance: AxiosInstance
constructor(baseURL: string) {
this.instance = axios.create({
baseURL
})
}
get<R = unknown>(url: string, query?: Record<string, JSONValue>, config?: GetConfig) {
return this.instance.request<R>({ ...config, url: url, params: query, method: 'get' })
}
post<R = unknown>(url: string, data?: Record<string, JSONValue>, config?: PostConfig) {
return this.instance.request<R>({ ...config, url, data, method: 'post' })
}
patch<R = unknown>(url: string, data?: Record<string, JSONValue>, config?: PatchConfig) {
return this.instance.request<R>({ ...config, url, data, method: 'patch' })
}
delete<R = unknown>(url: string, query?: Record<string, string>, config?: DeleteConfig) {
return this.instance.request<R>({ ...config, url: url, params: query, method: 'delete' })
}
}
const mock = (response: AxiosResponse) => {
if (location.hostname !== 'localhost'
&& location.hostname !== '127.0.0.1'
) { return false }
switch (response.config?.params?._mock) {
case 'session':
[response.status, response.data] = mockSession(response.config)
return true
}
return false
}
http.instance.interceptors.response.use((response) => {
mock(response)
return response
}, (error) => {
// 因为我们 mock 不会改变接口本身的响应状态,所以如果调用的接口本身请求失败还是会走 error,而我们 mock 是不希望有 error 的 所以我们这里直接把错误处理掉,这样才能在then里拿到数据
if (mock(error.response)) {
return error.response
} else {
throw error
}
})
- mock/mock.tsx
import { faker } from '@faker-js/faker'
import { AxiosRequestConfig } from 'axios';
type Mock = (config: AxiosRequestConfig) => [number, any]
faker.setLocale('zh_CN');
export const mockSession: Mock = (config) =>{
return [200, {
jwt: faker.random.word()
}]
}
使用
const response = await http.post<{jwt: string}>('/session', formData, {
params: { _mock: 'session' }
})
网友评论