YTRequest.ets 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. import axios, {
  2. AxiosError,
  3. AxiosHeaders,
  4. AxiosProgressEvent,
  5. AxiosRequestConfig,
  6. AxiosResponse,
  7. FormData,
  8. InternalAxiosRequestConfig
  9. } from '@ohos/axios';
  10. import { IBestToast, YTDate, YTLog, yTRouter } from '../../../../Index';
  11. import { AppStorageKeyCollect } from '../constants';
  12. import { ReqString } from '../models';
  13. import { userInfo, UserInfo } from '../models/UserInfo';
  14. import { HuaweiAuthPlugin } from './HuaWeiAuthPlugin';
  15. import { promptAction } from '@kit.ArkUI';
  16. // export const baseURL: string = 'https://hm-test.ytpm.net/prod-api'
  17. export const baseURL: string = 'https://hm.ytpm.net/prod-decision'
  18. export const instance = axios.create({
  19. baseURL,
  20. timeout: 5000
  21. })
  22. // 添加请求拦截器
  23. instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  24. // 对请求数据做点什么
  25. if (AppStorage.get<string>(AppStorageKeyCollect.TOKEN)) {
  26. config.headers.Authorization = AppStorage.get<string>(AppStorageKeyCollect.TOKEN)
  27. }
  28. return config;
  29. }, (error: AxiosError) => {
  30. // 对请求错误做些什么
  31. return Promise.reject(error);
  32. });
  33. // 添加响应拦截器
  34. instance.interceptors.response.use((response: AxiosResponse) => {
  35. // 对响应数据做点什么
  36. YTLog.info(response)
  37. // 对响应错误做点什么
  38. if (response.data.code == 401) {
  39. userInfo.logout()
  40. yTRouter.router2LoginPage()
  41. return Promise.reject('401');
  42. }
  43. return response.data.data;
  44. }, (error: AxiosError) => {
  45. YTLog.error(error)
  46. setTimeout(() => {
  47. IBestToast.hide()
  48. setTimeout(() => {
  49. IBestToast.show({ message: '请求超时,请检查网络' })
  50. }, 100)
  51. }, 1000)
  52. return Promise.reject(error);
  53. });
  54. export class YTRequest {
  55. private static productName: string = 'decisionApUser'
  56. static get<T>(url: string, params?: Record<string, string | number | boolean>,
  57. headers?: Record<string, string>): Promise<T> {
  58. return instance.get<null, T, null>(url, { params, headers })
  59. }
  60. static post<T, D>(url: string, data?: D, params?: Record<string, string | number | boolean>, headers?: AxiosHeaders) {
  61. return instance.post<null, T, D>(url, data, { params, headers })
  62. }
  63. static upPost<T, D>(url: string, data: D, configs?: AxiosRequestConfig<D>) {
  64. return instance.post<string, T, D>(url, data, configs)
  65. }
  66. //获取验证码
  67. static getCaptcha(phonenumber: string, success: (res: string) => void, fail: (err: Error) => void) {
  68. YTRequest.post<ReqString, ReqString>(`/${YTRequest.productName}/sendSmsCode`,
  69. { 'phonenumber': phonenumber })
  70. .then(res => {
  71. success(res['uuid'])
  72. })
  73. .catch((err: Error) => {
  74. fail(err)
  75. })
  76. }
  77. //手机号登录
  78. static phonenumberLogin(param: ReqString) {
  79. const uuid = AppStorage.get<string>('uuid')
  80. if (uuid !== undefined) {
  81. YTRequest.post<ReqString, ReqString>(`/${YTRequest.productName}/phoneLogin`, {
  82. 'phonenumber': param['phonenumber'],
  83. 'smsCode': param['captcha'],
  84. 'uuid': uuid
  85. })
  86. .then(res => {
  87. userInfo.setToken(res[AppStorageKeyCollect.TOKEN])
  88. YTRequest.refreshUserInfo(() => {
  89. IBestToast.show({ message: '登录成功' })
  90. yTRouter.routerBack()
  91. })
  92. })
  93. }
  94. }
  95. //华为登录
  96. static huaweiLogin() {
  97. try {
  98. IBestToast.showLoading()
  99. HuaweiAuthPlugin.requestAuth()
  100. .then(res => {
  101. YTRequest.post<ReqString, ReqString>(`/${YTRequest.productName}/hmLogin`,
  102. { 'code': res } as ReqString)
  103. .then(data => {
  104. const token = data['token']
  105. userInfo.setToken(token)
  106. YTRequest.refreshUserInfo((userInfo) => {
  107. // YTLog.info(userInfo)
  108. IBestToast.hide()
  109. setTimeout(() => {
  110. IBestToast.show({ message: '登录成功' })
  111. }, 100)
  112. yTRouter.routerBack()
  113. })
  114. })
  115. .catch((err: Error) => {
  116. // AlertDialog.show({ message: JSON.stringify(err, null, 2) })
  117. // IBestToast.hide()
  118. YTLog.error(err)
  119. })
  120. })
  121. .catch((e: Error) => {
  122. // AlertDialog.show({ message: JSON.stringify(e, null, 2) })
  123. YTLog.error(e)
  124. // IBestToast.hide()
  125. })
  126. } catch (e) {
  127. // AlertDialog.show({ message: JSON.stringify(e, null, 2) })
  128. YTLog.error(e)
  129. // IBestToast.hide()
  130. }
  131. }
  132. //刷新用户信息
  133. static refreshUserInfo(success?: (res: UserInfo) => void) {
  134. YTRequest.post<UserInfo, null>(`/${YTRequest.productName}/info`)
  135. .then(res => {
  136. userInfo.setUserInfoAndLogin(res)
  137. YTLog.info(userInfo)
  138. success?.(res)
  139. })
  140. }
  141. //上传文件
  142. static uploadFile(context: Context, fullpath: string, success: (url: string) => void) {
  143. const formData = new FormData()
  144. formData.append('file', fullpath)
  145. YTRequest.upPost<ReqString, FormData>('/common/upload', formData, {
  146. headers: { 'Content-Type': 'multipart/form-data' },
  147. context,
  148. onUploadProgress: (progressEvent: AxiosProgressEvent): void => {
  149. YTLog.info(progressEvent && progressEvent.loaded && progressEvent.total ?
  150. Math.ceil(progressEvent.loaded / progressEvent.total * 100) + '%' : '0%', 'uploadFile');
  151. }
  152. })
  153. .then(res => {
  154. const url = res['url']
  155. success(url)
  156. })
  157. }
  158. // 修改用户头像
  159. static uploadHeadImg(context: Context, fullpath: string, success: () => void) {
  160. const formData = new FormData()
  161. formData.append('file', fullpath)
  162. YTRequest.upPost<ReqString, FormData>('/common/upload', formData, {
  163. headers: { 'Content-Type': 'multipart/form-data' },
  164. context,
  165. onUploadProgress: (progressEvent: AxiosProgressEvent): void => {
  166. YTLog.info(progressEvent && progressEvent.loaded && progressEvent.total ?
  167. Math.ceil(progressEvent.loaded / progressEvent.total * 100) + '%' : '0%', 'uploadFile');
  168. }
  169. })
  170. .then(res => {
  171. const url = res['url']
  172. YTRequest.post<null, ReqString>(`/${YTRequest.productName}/modifyMemberIcon`, { 'memberIcon': url })
  173. .then(() => {
  174. success()
  175. })
  176. .catch((e: Error) => {
  177. YTLog.error(e)
  178. // IBestToast.show({ message: '头像上传失败', type: 'fail' })
  179. })
  180. })
  181. .catch((e: Error) => {
  182. YTLog.error(e)
  183. })
  184. }
  185. // 修改用户昵称
  186. static changeNickname(name: string, success: () => void) {
  187. YTRequest.post<null, ReqString>(`/${YTRequest.productName}/modifyMemberName`, { 'memberName': name })
  188. .then(() => {
  189. YTRequest.refreshUserInfo(() => {
  190. success()
  191. })
  192. })
  193. }
  194. //问题反馈
  195. static questionBack(des: string, createBy: string) {
  196. YTRequest.post<null, ReqString>(`/decisionBack/saveQuestion`, {
  197. 'backQuestion': des,
  198. 'createBy': createBy,
  199. // 'createTime': new YTDate().formatDate(),
  200. // 'createTime': new YTDate().toString()
  201. })
  202. .then(() => {
  203. IBestToast.show("反馈成功")
  204. yTRouter.routerBack()
  205. })
  206. .catch((e: Error) => {
  207. YTLog.error(e)
  208. })
  209. }
  210. }