ts 简易封装 axios,统一 API

文章目录

    • 为什么要封装
    • 目标
    • 文件结构
    • 封装通用请求方法
    • 获得类型提示
    • http 方法
    • 文件上传
    • 使用示例
      • 实例化
      • post 请求
      • 类型提示
      • 文件上传
    • 总结
    • 完整代码:

为什么要封装

axios 本身已经很好用了,看似多次一举的封装则是为了让 axios 与项目解耦。
比如想要将网络请求换成 fetch,那么只需按之前暴露的 api 重新封装一下 fetch 即可,并不需要改动项目代码。

目标

  1. 统一请求API
  2. 使用接口数据时能有代码提示

文件结构

│  index.ts					# 实例化封装类实例
│
├─http
│      request.ts  			# 封装axios
│
└─moduleslogin.ts				# 业务模块upload.ts

封装通用请求方法

先封装一个通用的方法 request,然后在此基础上封装出 http 方法:

class HttpRequest {private readonly instance: AxiosInstance;constructor(config: AxiosRequestConfig) {this.instance = axios.create(config);}request<TReqBodyData, TResData, TResStructure = ResStructure<TResData>>(config: AxiosRequestConfig<TReqBodyData>): Promise<TResStructure> {return new Promise<TResStructure>((resolve, reject) => {this.instance.request<any, AxiosResponse<TResStructure>>(config).then(res => {// 返回接口数据resolve(res?.data);}).catch(err => reject(err));});}
}

获得类型提示

我希望在使用请求方法时,可以得到后端接口请求参数的提示,并且希望在使用响应结果时,也能得到类型提示。

因此设计了三个泛型:

  1. TReqBodyData:请求体类型
  2. TResStructure:接口响应结构类型
    1. TResData:接口响应 data 字段数据类型

并提供了一个默认的响应结构。使用时可以根据需要改成项目中通用的接口规则。当然在具体方法上也支持自定义响应接口结构,以适应一些不符合通用接口规则的接口。

/** 默认接口返回结构 */
export interface ResStructure<TResData = any> {code: number;data: TResData;msg?: string;
}

http 方法

由 request 方法封装出 http 方法同名的 api。

get<TReqBodyData, TResData, TResStructure = ResStructure<TResData>>(config?: AxiosRequestConfig<TReqBodyData>
): Promise<TResStructure> {return this.request({ ...config, method: "GET" });
}post<TReqBodyData, TResData, TResStructure = ResStructure<TResData>>(config: AxiosRequestConfig<TReqBodyData>
): Promise<TResStructure> {return this.request({ ...config, method: "POST" });
}
...

文件上传

文件上传一般使用 formdata,我们也可以简易封装一下。

uploadFile 方法接收 4 个参数:

  1. axios config 对象
  2. 表单内容
    1. 文件对象
    2. 文件对象的表单字段名
    3. hash
    4. 文件名
    5. 更多的表单数据(可通过泛型 TOtherFormData 指定类型)
  3. 上传进度回调
  4. 取消上传的 signal
export interface UploadFileParams<TOtherFormData = Record<string, any>>  {file: File | Blob;  // 文件对象fileHash?: string;  // hashfilename?: string;  // 文件名filed?: string;     // formdata 中文件对象的字段formData?: TOtherFormData; // 文件其他的参数(对象 key-value 将作为表单数据)
}/*** 文件上传* @param {AxiosRequestConfig} config axios 请求配置对象* @param {UploadFileParams} params 待上传文件及其一些参数* @param {(event: AxiosProgressEvent) => void} uploadProgress 上传进度的回调函数* @param {AbortSignal}cancelSignal 取消axios请求的 signal* @returns*/uploadFile<TOtherFormData>(config: AxiosRequestConfig,params: UploadFileParams<TOtherFormData>,uploadProgress?: (event: AxiosProgressEvent) => void,cancelSignal?: AbortSignal) {const formData = new window.FormData();// 设置默认文件表单字段为 fileconst customFilename = params.filed ?? "file";// 是否指定文件名,没有就用文件本来的名字if (params.filename) {formData.append(customFilename, params.file, params.filename);formData.append("filename", params.filename);} else {formData.append(customFilename, params.file);}// 添加文件 hashif (params.fileHash) {formData.append("fileHash", params.fileHash);}// 是否有文件的额外信息补充进表单if (params.formData) {Object.keys(params.formData).forEach(key => {const value = params.formData![key as keyof TOtherFormData];if (Array.isArray(value)) {value.forEach(item => {formData.append(`${key}[]`, item);});return;}formData.append(key, value as any);});}return this.instance.request({...config,method: "POST",timeout: 60 * 60 * 1000, // 60分钟data: formData,onUploadProgress: uploadProgress,signal: cancelSignal,headers: {"Content-type": "multipart/form-data;charset=UTF-8"}});}

使用示例

实例化

import HttpRequest from "./request";/** 实例化 */
const httpRequest = new HttpRequest({baseURL: "http://localhost:8080",timeout: 10000
});

post 请求

/** post 请求 */// 定义请求体类型
interface ReqBodyData {user: string;age: number;
}// 定义接口响应中 data 字段的类型
interface ResDataPost {token: string;
}export function postReq(data: ReqBodyData) {return httpRequest.post<ReqBodyData, ResDataPost>({url: "/__api/mock/post_test",data: data});
}
/** 发起请求 */
async function handleClickPost() {const res = await postReq({ user: "ikun", age: 18 });console.log(res);
}

类型提示

获得使用请求方法时的请求接口参数类型提示:

获得请求接口时的参数类型提示

获得接口默认响应结构的提示:

获得接口默认响应结构的提示

  • 如果个别方法响应结构特殊,则可传入第三个泛型,自定义当前方法的响应结构
// 响应结构
interface ResStructure {code: number;list: string[];type: string;time: number;
}
function postReq(data: ReqBodyData) {return httpRequest.post<ReqBodyData, any, ResStructure>({url: "/__api/mock/post_test",data: data});
}

当前方法自定义接口响应结构:

自定义响应结构

获得接口响应中 data 字段的提示:

获得接口响应中 data 字段的提示

文件上传

/*** 文件上传*/interface OtherFormData {fileSize: number;
}function uploadFileReq(fileInfo: UploadFileParams<OtherFormData>,onUploadProgress?: (event: AxiosProgressEvent) => void,signal?: AbortSignal
) {return httpRequest.uploadFile<OtherFormData>({baseURL: import.meta.env.VITE_APP_UPLOAD_BASE_URL,url: "/upload"},fileInfo,onUploadProgress,signal);
}
// 发起请求const controller = new AbortController();async function handleClickUploadFile() {const file = new File(["hello"], "hello.txt", { type: "text/plain" });const res = await uploadFileReq({ file, fileHash: "xxxx", filename: "hello.txt", formData: { fileSize: 1024 } },event => console.log(event.loaded),controller.signal);console.log(res);
}

总结

  1. 在通用请求方法 request 基础上封装了同名的 http 方法
  2. 使用泛型可获得请求参数和请求结果的类型提示
  3. 额外封装了文件上传的方法

完整代码:

import axios, { AxiosInstance, AxiosProgressEvent, AxiosRequestConfig, AxiosResponse } from "axios";export interface UploadFileParams<TOtherFormData = Record<string, any>> {file: File | Blob;fileHash?: string;filename?: string;filed?: string;formData?: TOtherFormData; // 文件其他的参数(对象 key-value 将作为表单数据)
}/** 默认接口返回结构 */
export interface ResStructure<TResData = any> {code: number;data: TResData;msg?: string;
}/*** A wrapper class for making HTTP requests using Axios.* @class HttpRequest* @example* // Usage example:* const httpRequest = new HttpRequest({baseURL: 'http://localhost:8888'});* httpRequest.get<TReqBodyData, TResData, TResStructure>({ url: '/users/1' })*   .then(response => {*     console.log(response.name); // logs the name of the user*   })*   .catch(error => {*     console.error(error);*   });** @property {AxiosInstance} instance - The Axios instance used for making requests.*/
class HttpRequest {private readonly instance: AxiosInstance;constructor(config: AxiosRequestConfig) {this.instance = axios.create(config);}/*** Sends a request and returns a Promise that resolves with the response data.* @template TReqBodyData - The type of the request body.* @template TResData - The type of the `data` field in the `{code, data}` response structure.* @template TResStructure - The type of the response structure. The default is `{code, data, msg}`.* @param {AxiosRequestConfig} [config] - The custom configuration for the request.* @returns {Promise<TResStructure>} - A Promise that resolves with the response data.* @throws {Error} - If the request fails.** @example* // Sends a GET request and expects a response with a JSON object.* const response = await request<any, {name: string}>({*   method: 'GET',*   url: '/users/1',* });* console.log(response.name); // logs the name of the user*/request<TReqBodyData, TResData, TResStructure = ResStructure<TResData>>(config: AxiosRequestConfig<TReqBodyData>): Promise<TResStructure> {return new Promise<TResStructure>((resolve, reject) => {this.instance.request<any, AxiosResponse<TResStructure>>(config).then(res => {// 返回接口数据resolve(res?.data);}).catch(err => reject(err));});}/*** 发送 GET 请求* @template TReqBodyData 请求体数据类型* @template TResData 接口响应 data 字段数据类型* @template TResStructure 接口响应结构,默认为 {code, data, msg}* @param {AxiosRequestConfig} config 请求配置* @returns {Promise} 接口响应结果*/get<TReqBodyData, TResData, TResStructure = ResStructure<TResData>>(config?: AxiosRequestConfig<TReqBodyData>): Promise<TResStructure> {return this.request({ ...config, method: "GET" });}/*** 发送 post 请求* @template TReqBodyData 请求体数据类型* @template TResData 接口响应 data 字段数据类型* @template TResStructure 接口响应结构,默认为 {code, data, msg}* @param {AxiosRequestConfig} config 请求配置* @returns {Promise} 接口响应结果*/post<TReqBodyData, TResData, TResStructure = ResStructure<TResData>>(config: AxiosRequestConfig<TReqBodyData>): Promise<TResStructure> {return this.request({ ...config, method: "POST" });}patch<TReqBodyData, TResData, TResStructure = ResStructure<TResData>>(config: AxiosRequestConfig<TReqBodyData>): Promise<TResStructure> {return this.request({ ...config, method: "PATCH" });}delete<TReqBodyData, TResData, TResStructure = ResStructure<TResData>>(config?: AxiosRequestConfig<TReqBodyData>): Promise<TResStructure> {return this.request({ ...config, method: "DELETE" });}/*** 获取当前 axios 实例*/getInstance(): AxiosInstance {return this.instance;}/*** 文件上传* @param {AxiosRequestConfig} config axios 请求配置对象* @param {UploadFileParams} params 待上传文件及其一些参数* @param {(event: AxiosProgressEvent) => void} uploadProgress 上传进度的回调函数* @param {AbortSignal}cancelSignal 取消axios请求的 signal* @returns*/uploadFile<TOtherFormData = any>(config: AxiosRequestConfig,params: UploadFileParams<TOtherFormData>,uploadProgress?: (event: AxiosProgressEvent) => void,cancelSignal?: AbortSignal) {const formData = new window.FormData();// 设置默认文件表单字段为 fileconst customFilename = params.filed || "file";// 是否指定文件名,没有就用文件本来的名字if (params.filename) {formData.append(customFilename, params.file, params.filename);formData.append("filename", params.filename);} else {formData.append(customFilename, params.file);}// 添加文件 hashif (params.fileHash) {formData.append("fileHash", params.fileHash);}// 是否有文件的额外信息补充进表单if (params.formData) {Object.keys(params.formData).forEach(key => {const value = params.formData![key as keyof TOtherFormData];if (Array.isArray(value)) {value.forEach(item => {// 对象属性值为数组时,表单字段加一个[]formData.append(`${key}[]`, item);});return;}formData.append(key, value as any);});}return this.instance.request({...config,method: "POST",timeout: 60 * 60 * 1000, // 60分钟data: formData,onUploadProgress: uploadProgress,signal: cancelSignal,headers: {"Content-type": "multipart/form-data;charset=UTF-8"}});}
}export default HttpRequest;

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/155790.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

超强Redis基础学习 优化 使用 常见问题

问题大纲 为什么Redis可以这么快&#xff1f; 它是纯内存操作&#xff0c;内存本身就很快 其次&#xff0c;它是单线程的&#xff0c;Redis服务器核心是基于非阻塞的IO多路复用机制&#xff0c;单线程避免了多线程的频繁上下文切换问题 Redis的持久化机制 Redis提供了持久化…

计算机毕业设计选题推荐-跑腿平台微信小程序/安卓APP-项目实战

✨作者主页&#xff1a;IT研究室✨ 个人简介&#xff1a;曾从事计算机专业培训教学&#xff0c;擅长Java、Python、微信小程序、Golang、安卓Android等项目实战。接项目定制开发、代码讲解、答辩教学、文档编写、降重等。 ☑文末获取源码☑ 精彩专栏推荐⬇⬇⬇ Java项目 Python…

Ansible自动化运维工具介绍与部属

Ansible自动化运维工具介绍与部属 一、ansible简介1.1、什么是Ansible1.2、Ansible的特点1.3、Ansible的架构 二、Ansible任务执行解析2.1、ansible任务执行模式2.2、ansible执行流程2.3、ansible命令执行过程 三、部署ansible管理集群3.1、实验环境3.2、安装ansible3.3、查看基…

警惕听力下降的七大因素,一定要当心

随着现代社会的高速发展&#xff0c;工作生活节奏的加快&#xff0c;各种压力增大&#xff0c;再加上熬夜&#xff0c;长期佩戴耳机、饮食油腻辛辣等不良生活习惯的影响&#xff0c;听力损伤人群越来越多&#xff0c;已经不仅仅影响老年人群&#xff0c;近年来&#xff0c;听力…

OpenGL ES相关库加载3D 车辆模型

需求类似奇瑞的这个效果&#xff0c;就是能全方位旋转拖拽看车&#xff0c;以及点击开关车门车窗后备箱等 瑞虎9全景看车 (chery.cn) 最开始收到这个需求的时候还有点无所适从&#xff0c;因为以前没有做过类似的效果&#xff0c;后面一经搜索后发现实现的方式五花八门&#xf…

SpringBoot -- 请求数据多态映射(jackson)

有些情况下&#xff0c;服务端提供了一个抽象类及其多个实现类&#xff0c;当前端传递 json 数据到后端时&#xff0c;我们希望映射得到的对象数据是根据某个特征区分开的具体的实现类对象。 文章目录 实现方式示例抽象类对象若干实现类测试接口及前端传递请求体接参结果 JsonT…

API Testing v0.0.14 新增 gRPC, tRPC 协议的支持

api-testing 本次版本发布中的内容中&#xff0c;包含了两位高校同学的 contribution&#xff0c;其中屈晗煜在GitLink编程夏令营&#xff08;GLCC&#xff09;活动期间非常给力地增加了gRPC 协议的支持。 atest 版本发布 v0.0.14 atest 是一款用 Golang 编写的、开源的接口测试…

设备树(以STM32MP1为例)

1.设备树&#xff08;Device Tree&#xff09; 是一种用于描述硬件信息和配置的数据结构&#xff0c;以提供一个统一的方式来描述各种硬件设备的特性和连接方式。 设备树并不是从开始就存在&#xff0c;而是后来加入到Linux中&#xff0c;设备树主要用来描述系统的硬件结构 它是…

【智能座舱系列】- 深度解密小米Hyper OS,华为HarmonyOS区别

上一篇文章《小米的澎湃OS到底牛不牛?与鸿蒙系统之间差距有多大》,从多个方面比较了小米Hyper OS 与 华为HarmonyOS的区别,本篇文章继续从架构层面深度解读两者本质的区别。 小米澎湃OS是“以人为中心,打造人车家全生态操作系统”,该系统基于深度进化的Android以及自研的V…

【JAVA】类与对象的重点解析

个人主页&#xff1a;【&#x1f60a;个人主页】 系列专栏&#xff1a;【❤️初识JAVA】 文章目录 前言类与对象的关系JAVA源文件有关类的重要事项static关键字 前言 Java是一种面向对象编程语言&#xff0c;OOP是Java最重要的概念之一。学习OOP时&#xff0c;学生必须理解面向…

笔记软件Notability mac中文版软件功能

Notability mac是一款帮助用户备注文件的得力工具&#xff0c;Notability Mac版可用于注释文稿、草拟想法、录制演讲、记录备注等。它将键入、手写、录音和照片结合在一起&#xff0c;便于您根据需要创建相应的备注。 Mac Notability mac中文版软件功能 将手写&#xff0c;照片…

【git】git拉取代码报错,fatal: refusing to merge unrelated histories问题解决

大家好&#xff0c;我是好学的小师弟。今天准备将之前写的代码&#xff0c;拉到新的工程文件夹(仓库)下面&#xff0c;用了pull命令&#xff0c;结果报错了&#xff0c;报错截图如下 $ git pull https://gitee.com/* #仓库地址 fatal: refusing to merge unrelated histor…