YTRequest.ets 7.0 KB

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