import axios, { AxiosError, AxiosHeaders, AxiosProgressEvent, AxiosRequestConfig, AxiosResponse, FormData, InternalAxiosRequestConfig } from '@ohos/axios'; import { IBestToast, YTLog } from '../../../../Index'; import { reqString } from '../models'; import { UserInfo, userInfo } from '../models/UserInfo'; import { formatDate } from './FormatDate'; import { huaweiAuthPlugin } from './HuaWeiAuthPlugin'; import { yTRouter } from './YTRouter'; export const baseURL: string = 'https://hm-test.ytpm.net/prod-api' export const instance = axios.create({ baseURL, timeout: 5000 }) // 添加请求拦截器 instance.interceptors.request.use((config: InternalAxiosRequestConfig) => { // 对请求数据做点什么 if (AppStorage.get('token')) { config.headers.Authorization = AppStorage.get('token') } return config; }, (error: AxiosError) => { // 对请求错误做些什么 return Promise.reject(error); }); // 添加响应拦截器 instance.interceptors.response.use((response: AxiosResponse) => { // 对响应数据做点什么 YTLog.info(response) // 对响应错误做点什么 if (response.data.code == 401) { yTRouter.router2LoginPage() return Promise.reject('401'); } return response.data.data; }, (error: AxiosError) => { YTLog.error(error) setTimeout(() => { IBestToast.hide() setTimeout(() => { IBestToast.show({ message: '请求超时,请检查网络' }) }, 100) }, 1000) return Promise.reject(error); }); class YtRequest { private productName: string = 'chat' get(url: string, params?: Record, headers?: Record): Promise { return instance.get(url, { params, headers }) } post(url: string, data?: D, params?: Record, headers?: AxiosHeaders) { return instance.post(url, data, { params, headers }) } upPost(url: string, data: D, configs?: AxiosRequestConfig) { return instance.post(url, data, configs) } //获取验证码 getCaptcha(phonenumber: string, success: (res: string) => void, fail: (err: Error) => void) { yTRequest.post(`/api/${this.productName}/member/sendSmsCode`, { 'phonenumber': phonenumber }) .then(res => { success(res['uuid']) }) .catch((err: Error) => { fail(err) }) } //手机号登录 phonenumberLogin(param: reqString) { const uuid = AppStorage.get('uuid') if (uuid !== undefined) { yTRequest.post(`/api/${this.productName}/member/phoneLogin`, { 'phonenumber': param['phonenumber'], 'smsCode': param['captcha'], 'uuid': uuid }) .then(res => { userInfo.setToken(res['token']) yTRequest.refreshUserInfo(() => { IBestToast.show({ message: '登录成功' }) yTRouter.routerBack() }) }) } } //华为登录 huaweiLogin() { try { IBestToast.showLoading() huaweiAuthPlugin.requestAuth() .then(res => { yTRequest.post(`/api/${this.productName}/member/hmLogin`, { 'code': res } as reqString) .then(data => { const token = data['token'] userInfo.setToken(token) yTRequest.refreshUserInfo((userInfo) => { // YTLog.info(userInfo) IBestToast.hide() setTimeout(() => { IBestToast.show({ message: '登录成功' }) }, 100) yTRouter.routerBack() }) }) .catch((err: Error) => { // AlertDialog.show({ message: JSON.stringify(err, null, 2) }) // IBestToast.hide() YTLog.error(err) }) }) .catch((e: Error) => { // AlertDialog.show({ message: JSON.stringify(e, null, 2) }) YTLog.error(e) // IBestToast.hide() }) } catch (e) { // AlertDialog.show({ message: JSON.stringify(e, null, 2) }) YTLog.error(e) // IBestToast.hide() } } //刷新用户信息 refreshUserInfo(success?: (res: UserInfo) => void) { yTRequest.post(`/api/${this.productName}/member/info`) .then(res => { userInfo.setUserInfoAndLogin(res) YTLog.info(userInfo) success?.(res) }) } //上传文件 uploadFile(context: Context, fullpath: string, success: (url: string) => void) { const formData = new FormData() formData.append('file', fullpath) yTRequest.upPost('/common/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' }, context, onUploadProgress: (progressEvent: AxiosProgressEvent): void => { YTLog.info(progressEvent && progressEvent.loaded && progressEvent.total ? Math.ceil(progressEvent.loaded / progressEvent.total * 100) + '%' : '0%', 'uploadFile'); } }) .then(res => { const url = res['url'] success(url) }) } // 修改用户头像 uploadHeadImg(context: Context, fullpath: string, success: () => void) { const formData = new FormData() formData.append('file', fullpath) yTRequest.upPost('/common/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' }, context, onUploadProgress: (progressEvent: AxiosProgressEvent): void => { YTLog.info(progressEvent && progressEvent.loaded && progressEvent.total ? Math.ceil(progressEvent.loaded / progressEvent.total * 100) + '%' : '0%', 'uploadFile'); } }) .then(res => { const url = res['url'] yTRequest.post(`/api/${this.productName}/member/modifyMemberIcon`, { 'memberIcon': url }) .then(() => { success() }) .catch((e: Error) => { YTLog.error(e) // IBestToast.show({ message: '头像上传失败', type: 'fail' }) }) }) .catch((e: Error) => { YTLog.error(e) }) } // 修改用户昵称 changeNickname(name: string, success: () => void) { yTRequest.post(`/api/${this.productName}/member/modifyMemberName`, { 'memberName': name }) .then(() => { yTRequest.refreshUserInfo(() => { success() }) }) } //问题反馈 questionBack(des: string, createBy: string) { yTRequest.post(`/api/${this.productName}/question/saveQuestion`, { 'backQuestion': des, 'createBy': createBy, 'createTime': formatDate(new Date()), 'id': userInfo.getId()?.toString()! }) .then() .catch((e: Error) => { YTLog.error(e) }) } } export const yTRequest = new YtRequest()