封装UTS的uni.request()的请求

438 阅读1分钟

封装

// 定义一个请求之前回调函数类型
type BeforeRequestFunction = (data : Request) => void;
// 定义一个请求之后回调函数类型
type AfterRequestFunction = ((option : any) => void);
/**
 * 转换GET请求参数
 */
const $JsonAndArrayTOString = (data : UTSJSONObject | null) : string => {
	if (data === null) return ""
	let str = "?"
	for (var key in data) {
		if (Array.isArray(data[key])) {
			var arr : any[] = data[key] as any[]
			arr.forEach((item : any) => {
				str += `${key}[]=${item}&`
			})
		} else {
			str += `${key}=${data[key]}&`
		}
	}
	return str.slice(0, -1) // 去除末尾的 &
}

class Request {
	private data : any | null
	private baseUrl : string | null
	private parametUrl : string | null
	private url : string
	private method : RequestMethod
	private timeout : number
	private header : UTSJSONObject
	private requestTag ?: RequestTask
	private beforeRequest ?: BeforeRequestFunction
	private afterRequest ?: AfterRequestFunction
	/**
	 * 初始化对象
	 */
	constructor() {
		// 请求的根路径
		this.baseUrl = null
		// 请求的 url 地址
		this.parametUrl = null
		// 请求的 url 地址
		this.url = ""
		// 请求方式
		this.method = 'GET'
		// 请求的参数对象
		this.data = null
		// 超时时间,单位 ms
		this.timeout = 6000
		// header 请求头
		this.header = new UTSJSONObject()
		// 请求之前回调 
		this.beforeRequest = null
		// 请求之后回调
		this.afterRequest = null
		// requestTask 对象
		this.requestTag = null
	}
	/**
	 * 设置基础Url
	 */
	setBaseUrl(baseUrl : string) {
		this.baseUrl = baseUrl;
	}
	/**
	 * 设置超时时间
	 */
	setTimeout(timeout : number) {
		this.timeout = timeout
	}
	/**
	 * 设置请求头
	 */
	addHeader(key : string, value : any) {
		this.header.set(key, value)
	}
	/**
	 * 设置请求前回调
	 */
	setBeforeRequest(beforeRequest : BeforeRequestFunction) {
		this.beforeRequest = beforeRequest
	}
	/**
	 * 设置请求后回调
	 */
	setAfterRequest(afterRequest : AfterRequestFunction) {
		this.afterRequest = afterRequest
	}
	/**
	 * 中断请求任务
	 */
	setAbrot() {
		requestTag?.abort()
	}
	/**
	 * 获取参数url地址
	 */
	getParametUrl() : string | null {
		return this.parametUrl
	}

	get(url : string, data : UTSJSONObject | null) : Promise<any> {
		this.method = 'GET'
		this.url = `${this.baseUrl}${url}${$JsonAndArrayTOString(data)}`
		this.parametUrl = url
		this.data = data
		return this.requset()
	}

	post(url : string, data : UTSJSONObject | null) : Promise<any> {
		this.method = 'POST'
		this.url = `${this.baseUrl}${url}`
		this.parametUrl = url
		this.data = data
		return this.requset()
	}

	put(url : string, data : UTSJSONObject | null) : Promise<any> {
		this.method = 'PUT'
		this.url = `${this.baseUrl}${url}`
		this.parametUrl = url
		return this.requset()
	}

	delete(url : string, data : UTSJSONObject | null) : Promise<any> {
		this.method = 'DELETE'
		this.url = `${this.baseUrl}${url}${$JsonAndArrayTOString(data)}`
		this.parametUrl = url
		this.data = null
		return this.requset()
	}

	private requset() : Promise<any> {
		this.beforeRequest?.invoke(this)
		return new Promise((resolve, reject) => {
			uni.request({
				url: this.url,
				method: this.method,
				data: this.data,
				header: this.header,
				timeout: this.timeout,
				success: (res) => { resolve(res) },
				fail: (err) => { reject(err) },
				complete: (res) => {
					this.afterRequest?.invoke(res)
				}
			})
		})
	}
}
export const $http = new Request()

配置

import { $http } from "@/utils/Request";
$http.setTimeout(12000)
$http.setBaseUrl("https://xxx.xxx.com")
$http.setBeforeRequest((res) => {
    res.addHeader("Content-Type", "application/json")
    res.addHeader("Authorization", `Bearer ${11}`)
	console.log("请求前参数",res);
})
$http.setAfterRequest((res)=>{
	console.log("请求后参数",JSON.stringify(res));
})



export default $http

使用

import Api from "@/utils/RequsetPackage.uts"

export const Login = async (req : UTSJSONObject):Promise<any> => {
	let res = await Api.get("/api/login", req)
	return res
}