| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236 |
- import axios, {
- AxiosError,
- AxiosHeaders,
- AxiosProgressEvent,
- AxiosRequestConfig,
- AxiosResponse,
- FormData,
- InternalAxiosRequestConfig
- } from '@ohos/axios';
- import { IBestToast, YTDate, YTLog, yTRouter } from '../../../../Index';
- import { AppStorageKeyCollect } from '../constants';
- import { ReqString } from '../models';
- import { userInfo, UserInfo } from '../models/UserInfo';
- import { HuaweiAuthPlugin } from './HuaWeiAuthPlugin';
- import { promptAction } from '@kit.ArkUI';
- // export const baseURL: string = 'https://hm-test.ytpm.net/prod-api'
- export const baseURL: string = 'https://hm.ytpm.net/prod-decision'
- export const instance = axios.create({
- baseURL,
- timeout: 5000
- })
- // 添加请求拦截器
- instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
- // 对请求数据做点什么
- if (AppStorage.get<string>(AppStorageKeyCollect.TOKEN)) {
- config.headers.Authorization = AppStorage.get<string>(AppStorageKeyCollect.TOKEN)
- }
- return config;
- }, (error: AxiosError) => {
- // 对请求错误做些什么
- return Promise.reject(error);
- });
- // 添加响应拦截器
- instance.interceptors.response.use((response: AxiosResponse) => {
- // 对响应数据做点什么
- YTLog.info(response)
- // 对响应错误做点什么
- if (response.data.code == 401) {
- userInfo.logout()
- 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);
- });
- export class YTRequest {
- private static productName: string = 'decisionApUser'
- static get<T>(url: string, params?: Record<string, string | number | boolean>,
- headers?: Record<string, string>): Promise<T> {
- return instance.get<null, T, null>(url, { params, headers })
- }
- static post<T, D>(url: string, data?: D, params?: Record<string, string | number | boolean>, headers?: AxiosHeaders) {
- return instance.post<null, T, D>(url, data, { params, headers })
- }
- static upPost<T, D>(url: string, data: D, configs?: AxiosRequestConfig<D>) {
- return instance.post<string, T, D>(url, data, configs)
- }
- //获取验证码
- static getCaptcha(phonenumber: string, success: (res: string) => void, fail: (err: Error) => void) {
- YTRequest.post<ReqString, ReqString>(`/${YTRequest.productName}/sendSmsCode`,
- { 'phonenumber': phonenumber })
- .then(res => {
- success(res['uuid'])
- })
- .catch((err: Error) => {
- fail(err)
- })
- }
- //手机号登录
- static phonenumberLogin(param: ReqString) {
- const uuid = AppStorage.get<string>('uuid')
- if (uuid !== undefined) {
- YTRequest.post<ReqString, ReqString>(`/${YTRequest.productName}/phoneLogin`, {
- 'phonenumber': param['phonenumber'],
- 'smsCode': param['captcha'],
- 'uuid': uuid
- })
- .then(res => {
- userInfo.setToken(res[AppStorageKeyCollect.TOKEN])
- YTRequest.refreshUserInfo(() => {
- IBestToast.show({ message: '登录成功' })
- yTRouter.routerBack()
- })
- })
- }
- }
- //华为登录
- static huaweiLogin() {
- try {
- IBestToast.showLoading()
- HuaweiAuthPlugin.requestAuth()
- .then(res => {
- YTRequest.post<ReqString, ReqString>(`/${YTRequest.productName}/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()
- }
- }
- //刷新用户信息
- static refreshUserInfo(success?: (res: UserInfo) => void) {
- YTRequest.post<UserInfo, null>(`/${YTRequest.productName}/info`)
- .then(res => {
- userInfo.setUserInfoAndLogin(res)
- YTLog.info(userInfo)
- success?.(res)
- })
- }
- //上传文件
- static uploadFile(context: Context, fullpath: string, success: (url: string) => void) {
- const formData = new FormData()
- formData.append('file', fullpath)
- YTRequest.upPost<ReqString, FormData>('/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)
- })
- }
- // 修改用户头像
- static uploadHeadImg(context: Context, fullpath: string, success: () => void) {
- const formData = new FormData()
- formData.append('file', fullpath)
- YTRequest.upPost<ReqString, FormData>('/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<null, ReqString>(`/${YTRequest.productName}/modifyMemberIcon`, { 'memberIcon': url })
- .then(() => {
- success()
- })
- .catch((e: Error) => {
- YTLog.error(e)
- // IBestToast.show({ message: '头像上传失败', type: 'fail' })
- })
- })
- .catch((e: Error) => {
- YTLog.error(e)
- })
- }
- // 修改用户昵称
- static changeNickname(name: string, success: () => void) {
- YTRequest.post<null, ReqString>(`/${YTRequest.productName}/modifyMemberName`, { 'memberName': name })
- .then(() => {
- YTRequest.refreshUserInfo(() => {
- success()
- })
- })
- }
- //问题反馈
- static questionBack(des: string, createBy: string) {
- YTRequest.post<null, ReqString>(`/decisionBack/saveQuestion`, {
- 'backQuestion': des,
- 'createBy': createBy,
- // 'createTime': new YTDate().formatDate(),
- // 'createTime': new YTDate().toString()
- })
- .then(() => {
- IBestToast.show("反馈成功")
- yTRouter.routerBack()
- })
- .catch((e: Error) => {
- YTLog.error(e)
- })
- }
- }
|