TypeScript学习笔记之axios简单封装

TypeScript对比JavaScript最大的区别就是TypeScript是强类型的。这种强类型相比弱类型,可以在编译期间发现并纠正错误,降低了试错的成本(智能提示)也提升了代码的规范性。

axios封装

//http.ts

import axios, {AxiosInstance, AxiosRequestConfig, AxiosResponse} from 'axios'

const config = {
    baseURL: /*读取配置文件*/process.env.VUE_APP_BASE_API_URL,
    timeout: 10 * 1000,
    withCredentials: true
};

const requestInterceptor = (config: AxiosRequestConfig): AxiosRequestConfig => {
    //请求拦截器,自定义
    return config;
};

const http: AxiosInstance = axios.create(config);
http.interceptors.request.use(requestInterceptor, error => Promise.reject(error))
http.interceptors.response.use(response => Promise.resolve(response), error => Promise.reject(error))

export function httpRequest<T>(config: AxiosRequestConfig): Promise<T> {
    const promise = http.request<T, AxiosResponse<T>>(config);
    return convertAxiosResponse(promise);
}

export function httpGet<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    const promise = http.get<T, AxiosResponse<T>>(url, config);
    return convertAxiosResponse(promise);
}

export function httpDelete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    const promise = http.delete<T, AxiosResponse<T>>(url, config);
    return convertAxiosResponse(promise);
}

export function httpHead<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    const promise = http.head<T, AxiosResponse<T>>(url, config);
    return convertAxiosResponse(promise);
}

export function httpOptions<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    const promise = http.options<T, AxiosResponse<T>>(url, config);
    return convertAxiosResponse(promise);
}

export function httpPost<T, D>(url: string, data?: D, config?: AxiosRequestConfig): Promise<T> {
    const promise = http.post<T, AxiosResponse<T>, D>(url, data, config)
    return convertAxiosResponse(promise);
}

export function httpPut<T, D>(url: string, data?: D, config?: AxiosRequestConfig): Promise<T> {
    const promise = http.put<T, AxiosResponse<T>, D>(url, data, config);
    return convertAxiosResponse(promise);
}

export function httpPatch<T, D>(url: string, data?: D, config?: AxiosRequestConfig): Promise<T> {
    const promise = http.patch<T, AxiosResponse<T>, D>(url, data, config);
    return convertAxiosResponse(promise);
}

/**
 * @param axiosPromise AxiosResponse<T>
 */
function convertAxiosResponse<T>(axiosPromise: Promise<AxiosResponse<T>>): Promise<T> {
    return new Promise(function (resolve, reject) {
        axiosPromise.then(response => {
            resolve(response.data)
        }).then(err => {
            reject(err)
        });
    });
}

接口返回实体

因为是强类型的,支持泛型,所有我们可以把数据封装成一个实体类(或接口),这样参数就一目了然,类似Java中JavaBean的使用。
如果接口返回有统一的格式,如:

{
    "code": 200,
    "msg": "success",
    "data": any
}

那么就可以定义一个Base类(或接口),data以泛型参数传入。

//api-bean.ts

export interface ApiResponse<T = any> {
    code: number;
    msg: string;
    data: T;
}

export interface UserInfoBean {
    createdAt: string;
    id: number;
    userId: string;
    userType: string;
    username: string;
}

/**
 * 登录使用
 */
export interface UserLoginBean {
    userId: string;
    password: string;
    userType: string;
}

使用示例


import {httpGet, httpPost} from "@/util/http"
import {ApiResponse, UserInfoBean, UserLoginBean} from "@/bean/api-bean";

httpGet<ApiResponse<UserInfoBean[]>>("/srs_rtc/user/getAllUserInfo")
    .then((response) => {
      console.log("httpGet:", response)
    })
const login: UserLoginBean = {
  userId: "test",
  password: "1",
  userType: "0"
}
httpPost<ApiResponse<UserInfoBean>, UserLoginBean>("/srs_rtc/user/userLogin", login).then(response => {
  console.log("httpPost:", response)
}).then(error => {
  //
})

使用的时候就有智能提示了,相比JavaScript是不是爽很多?


示例

本人刚刚入手TypeScript,如有使用不当之处,欢迎指正。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容