比较喜欢链式调用的方式,需要设置什么参数,调用具体的方法,视觉和逻辑上简洁明了。实现一个基于axios的网络请求封装,实现链式调用的效果
1、使用方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| HttpHelper.newClient<DataBean>() .host("https://www.wanandroid.com") .api("article/list/0/json") .enableShowLoading(true) .enableShowToast(true) .params(Object({ "cid": 60 })) .onSuccess((info) => { data(info) }) .onError((error) => { }) .get() class TestViewModel { getListData2(data: (data?: DataBean) => void) { HttpHelper.newClient<DataBean>() .api("article/list/0/json") .params(Object({ "cid": 60 })) .onSuccess((info) => { data(info) }) .get() } }
|
2、实现方法
定义后端返回的数据格式,按需定义
1 2 3 4 5 6 7 8 9 10 11 12
| export interface BaseApiResponse<T> { errorCode?: number|string errorMsg?: string data?: T }
export interface BaseError { message: string; code?: number | string; }
|
实现类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
|
export class HttpHelper<T> { private baseUrl: string = "https://www.wanandroid.com" private timeOut: number = 10000
private requestApi?: string private paramsData?: object
private isShowLoadingDialog: boolean = true private isShowErrorToast: boolean = true private axiosInstance?: AxiosInstance;
private success?: (result?: T) => void; private error?: (result?: BaseError) => void;
private constructor() { }
private defaultConfig: AxiosRequestConfig = { baseURL: this.baseUrl, timeout: this.timeOut }
host(host: string): HttpHelper<T> { this.baseUrl = host return this; }
api(api?: string): HttpHelper<T> { this.requestApi = api return this }
params(params?: object): HttpHelper<T> { this.paramsData = params return this }
public static newClient<T>(): HttpHelper<T> { return new HttpHelper() }
get() { this.request(RequestType.GET) }
post() { this.request(RequestType.POST) }
put() { this.request(RequestType.PUT) }
delete() { this.request(RequestType.DELETE) }
onSuccess(success?: (result?: T) => void): HttpHelper<T> { this.success = success; return this; }
onError(error?: (result?: BaseError) => void): HttpHelper<T> { this.error = error; return this; }
enableShowLoading(enableLoading: boolean): HttpHelper<T> { this.isShowLoadingDialog = enableLoading; return this; }
enableShowToast(enable: boolean): HttpHelper<T> { this.isShowErrorToast = enable return this }
private updateBaseConfig() { this.defaultConfig.baseURL = this.baseUrl this.defaultConfig.timeout = this.timeOut
this.axiosInstance = axios.create(this.defaultConfig); this.initIntercept() }
private initIntercept() { this.axiosInstance?.interceptors.request.use((config: InternalAxiosRequestConfig) => { let info = `请求路径 ${config.baseURL}${config.url}\n请求参数 ${JSON.stringify(config.params)}` LogUtil.info(info) return config; }, (error: AxiosError) => { return Promise.reject(error); }); }
private showLoading() { if (this.isShowLoadingDialog) { LoadingDialog.getInstance().show() } }
private hideLoading() { if (this.isShowLoadingDialog) { LoadingDialog.getInstance().hide() } }
private showToast(message?: string) { if (this.isShowErrorToast && message) { ToastUtil.showShort(message) } }
private request(type: RequestType) {
this.updateBaseConfig() this.showLoading() let response: Promise<BaseResponse<BaseApiResponse<T>>>
switch (type) { case RequestType.GET: response = this.axiosInstance!.get<string, BaseResponse<BaseApiResponse<T>>>(this.requestApi, { params: this.paramsData }) break case RequestType.POST: response = this.axiosInstance!.post<string, BaseResponse<BaseApiResponse<T>>>(this.requestApi, { params: this.paramsData }) break case RequestType.PUT: response = this.axiosInstance!.put<string, BaseResponse<BaseApiResponse<T>>>(this.requestApi, { params: this.paramsData }) break case RequestType.DELETE: response = this.axiosInstance!.delete<string, BaseResponse<BaseApiResponse<T>>>(this.requestApi, { params: this.paramsData }) break
default: response = this.axiosInstance!.get<string, BaseResponse<BaseApiResponse<T>>>(this.requestApi, { params: this.paramsData }) break }
response.then((res) => { let data = res.data if (data.errorCode == 0) { if (this.success) { this.success(data.data) } } else { if (this.error) { let errBean: BaseError = { code: data.errorCode, message: data.errorMsg ?? "" } this.showToast(errBean.message) if (this.error) { this.error(errBean) } } } }).catch((error: AxiosError) => { let errBean: BaseError = { code: error.code, message: error.message }
this.showToast(errBean.message)
if (this.error) { this.error(errBean) } }).finally(() => { this.hideLoading()
}); } }
|
3、问题
当后端返回的数据类型不统一时可能无法正常使用,比如:
1 2 3 4 5 6 7 8 9 10 11
| { code:1 message:"" data:{...} }
{ errorCode:1 errorMsg:"" datas:{...} }
|
封装实现了分割请求成功和失败的两种情况,避免了各个接口请求的公共逻辑代码(如弹窗、错误信息显示),对于拿到手的数据可以更专注于请求成功后的逻辑处理,但是这样请求的数据格式在框架中就限制死了
1
| let response: Promise<BaseResponse<BaseApiResponse<T>>>
|
如果拿到了不是这个格式的数据,那么后续的逻辑处理都可能出现问题。
尝试过把BaseApiResponse整个当做HttpHelper的泛型传入,打算通过封装BaseApiResponse的子类来解决格式不统一的问题,但是,由于语言限制,好像鸿蒙中无法像android中json和对象互相映射的功能,android中可以创建多种数据格式的子类,利用多态特性,关系映射解决掉这个问题,但是鸿蒙好像还不行
华为官方关于Json解析成对象的相关说明 ,使用第三方映射库还是得传入实际的对象类型,暂时是想不到怎么在底层拿到上层的数据类型。
暂时没有比较完美的解决方式,本地端能处理的估计就是在拿到数据后如果已知数据格式不统一,在拦截器中修改成需要的数据类型。
不知道有没有大佬看到,希望不吝赐教。