YTRequest.ets 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. import axios, {
  2. AxiosError,
  3. AxiosHeaders,
  4. AxiosProgressEvent,
  5. AxiosRequestConfig,
  6. AxiosResponse,
  7. FormData,
  8. InternalAxiosRequestConfig
  9. } from '@ohos/axios';
  10. import { IBestToast, YTLog } from '../../../../Index';
  11. import { reqString } from '../models';
  12. import { UserInfo, userInfo } from '../models/UserInfo';
  13. import { formatDate } from './FormatDate';
  14. import { huaweiAuthPlugin } from './HuaWeiAuthPlugin';
  15. import { yTRouter } from './YTRouter';
  16. export const baseURL: string = 'https://hm-test.ytpm.net/prod-api'
  17. export const instance = axios.create({
  18. baseURL,
  19. timeout: 5000
  20. })
  21. // 添加请求拦截器
  22. instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  23. // 对请求数据做点什么
  24. if (AppStorage.get<string>('token')) {
  25. config.headers.Authorization = AppStorage.get<string>('token')
  26. }
  27. return config;
  28. }, (error: AxiosError) => {
  29. // 对请求错误做些什么
  30. return Promise.reject(error);
  31. });
  32. // 添加响应拦截器
  33. instance.interceptors.response.use((response: AxiosResponse) => {
  34. // 对响应数据做点什么
  35. YTLog.info(response)
  36. // 对响应错误做点什么
  37. if (response.data.code == 401) {
  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. class YtRequest {
  53. private productName: string = 'chat'
  54. 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. 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. upPost<T, D>(url: string, data: D, configs?: AxiosRequestConfig<D>) {
  62. return instance.post<string, T, D>(url, data, configs)
  63. }
  64. //获取验证码
  65. getCaptcha(phonenumber: string, success: (res: string) => void, fail: (err: Error) => void) {
  66. yTRequest.post<reqString, reqString>(`/api/${this.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. phonenumberLogin(param: reqString) {
  77. const uuid = AppStorage.get<string>('uuid')
  78. if (uuid !== undefined) {
  79. yTRequest.post<reqString, reqString>(`/api/${this.productName}/member/phoneLogin`, {
  80. 'phonenumber': param['phonenumber'],
  81. 'smsCode': param['captcha'],
  82. 'uuid': uuid
  83. })
  84. .then(res => {
  85. userInfo.setToken(res['token'])
  86. yTRequest.refreshUserInfo(() => {
  87. IBestToast.show({ message: '登录成功' })
  88. yTRouter.routerBack()
  89. })
  90. })
  91. }
  92. }
  93. //华为登录
  94. huaweiLogin() {
  95. try {
  96. IBestToast.showLoading()
  97. huaweiAuthPlugin.requestAuth()
  98. .then(res => {
  99. yTRequest.post<reqString, reqString>(`/api/${this.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. refreshUserInfo(success?: (res: UserInfo) => void) {
  132. yTRequest.post<UserInfo, null>(`/api/${this.productName}/member/info`)
  133. .then(res => {
  134. userInfo.setUserInfoAndLogin(res)
  135. YTLog.info(userInfo)
  136. success?.(res)
  137. })
  138. }
  139. //上传文件
  140. 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. 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/${this.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. changeNickname(name: string, success: () => void) {
  185. yTRequest.post<null, reqString>(`/api/${this.productName}/member/modifyMemberName`, { 'memberName': name })
  186. .then(() => {
  187. yTRequest.refreshUserInfo(() => {
  188. success()
  189. })
  190. })
  191. }
  192. //问题反馈
  193. questionBack(des: string, createBy: string) {
  194. yTRequest.post<null, reqString>(`/api/${this.productName}/question/saveQuestion`, {
  195. 'backQuestion': des,
  196. 'createBy': createBy,
  197. 'createTime': formatDate(new Date()),
  198. 'id': userInfo.getId()?.toString()!
  199. })
  200. .then()
  201. .catch((e: Error) => {
  202. YTLog.error(e)
  203. })
  204. }
  205. }
  206. export const yTRequest = new YtRequest()