YTRequest.ets 6.9 KB

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