TypeScript封装微信小程序请求实战

孟振
2023-12-01

前言
最近第一次做原生微信小程序,之前都是采用Taro、uni这两个第三方框架,发现微信原生小程序支持了TypeScript,于是尝试了使用ts结合Promise封装了微信简易请求库,不得不说,写ts确实可以减少动态语言(JS)带来的bug,如下:

const host = 'xxx';

/**
 * http请求配置
*/
interface RequestConfig {
    url: String;
    method?: HttpMethod;
    data?: any;
    needToken?: Boolean;
    header?: Object
}

/**
 * http请求方法枚举
*/
enum HttpMethod {
    GET,
    POST
}


class HttpRequest {

    private static instance: HttpRequest;

	private constructor() {}

    /**
     * 单例
    */
    public static getInstance(): HttpRequest {
        if (!this.instance) {
            this.instance = new HttpRequest();
        }
		
        return this.instance;
    }



	/**
	 * 公用请求方法
	*/
	public request(requestConfig: RequestConfig): Promise<Object> {
        return new Promise((resolve, reject) => {
            let header = {
              'content-type': 'application/json',
			};
            wx.request({
              method: requestConfig.method === HttpMethod.GET ? "GET" : "POST",
              url: `${host}${requestConfig.url}`,
              data: requestConfig.data,
              header: Object.assign(header, requestConfig?.header),
              success:(res) => resolve(res.data),
              fail:(err) =>  reject(err),
            });
        });
    }

	/**
	 * url:请求url
	 * config: 包括请求头
	*/
    public get(url: string, config?:Object):Promise<Object> {
        return this.request({ url, method: HttpMethod.GET, ...config })
    }

    public post(url: string, data: Object, config?:Object):Promise<Object>  {
        return this.request({ url, method: HttpMethod.POST, data, ...config })
    }

}

export default HttpRequest.getInstance();

三种调用

import http  from 'xxx';
http({ methods: "POST",url: 'xxx', data, header });
http.post('xxx', params, { header: { 'Content-Type'= 'application/x-www-form-urlencoded'}})
http.get('xxx', config);

总结
感谢你的观看,若有写的不对、不合理的地方,希望大家指出。

 类似资料: