| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234 |
- import axios, {
- AxiosError,
- AxiosHeaders,
- AxiosProgressEvent,
- AxiosRequestConfig,
- AxiosResponse,
- FormData,
- InternalAxiosRequestConfig
- } from '@ohos/axios';
- import { IBestToast, YTLog } from '../../../../Index';
- import { reqString } from '../models';
- import { UserInfo, userInfo } from '../models/UserInfo';
- import { formatDate } from './FormatDate';
- import { huaweiAuthPlugin } from './HuaWeiAuthPlugin';
- import { yTRouter } from './YTRouter';
- export const baseURL: string = 'https://hm-test.ytpm.net/prod-api'
- export const instance = axios.create({
- baseURL,
- timeout: 5000
- })
- // 添加请求拦截器
- instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
- // 对请求数据做点什么
- if (AppStorage.get<string>('token')) {
- config.headers.Authorization = AppStorage.get<string>('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);
- });
- class YtRequest {
- private productName: string = 'chat'
- 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 })
- }
- 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 })
- }
- upPost<T, D>(url: string, data: D, configs?: AxiosRequestConfig<D>) {
- return instance.post<string, T, D>(url, data, configs)
- }
- //获取验证码
- getCaptcha(phonenumber: string, success: (res: string) => void, fail: (err: Error) => void) {
- yTRequest.post<reqString, reqString>(`/api/${this.productName}/member/sendSmsCode`,
- { 'phonenumber': phonenumber })
- .then(res => {
- success(res['uuid'])
- })
- .catch((err: Error) => {
- fail(err)
- })
- }
- //手机号登录
- phonenumberLogin(param: reqString) {
- const uuid = AppStorage.get<string>('uuid')
- if (uuid !== undefined) {
- yTRequest.post<reqString, reqString>(`/api/${this.productName}/member/phoneLogin`, {
- 'phonenumber': param['phonenumber'],
- 'smsCode': param['captcha'],
- 'uuid': uuid
- })
- .then(res => {
- userInfo.setToken(res['token'])
- yTRequest.refreshUserInfo(() => {
- IBestToast.show({ message: '登录成功' })
- yTRouter.routerBack()
- })
- })
- }
- }
- //华为登录
- huaweiLogin() {
- try {
- IBestToast.showLoading()
- huaweiAuthPlugin.requestAuth()
- .then(res => {
- yTRequest.post<reqString, reqString>(`/api/${this.productName}/member/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()
- }
- }
- //刷新用户信息
- refreshUserInfo(success?: (res: UserInfo) => void) {
- yTRequest.post<UserInfo, null>(`/api/${this.productName}/member/info`)
- .then(res => {
- userInfo.setUserInfoAndLogin(res)
- YTLog.info(userInfo)
- success?.(res)
- })
- }
- //上传文件
- 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)
- })
- }
- // 修改用户头像
- 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>(`/api/${this.productName}/member/modifyMemberIcon`, { 'memberIcon': url })
- .then(() => {
- success()
- })
- .catch((e: Error) => {
- YTLog.error(e)
- // IBestToast.show({ message: '头像上传失败', type: 'fail' })
- })
- })
- .catch((e: Error) => {
- YTLog.error(e)
- })
- }
- // 修改用户昵称
- changeNickname(name: string, success: () => void) {
- yTRequest.post<null, reqString>(`/api/${this.productName}/member/modifyMemberName`, { 'memberName': name })
- .then(() => {
- yTRequest.refreshUserInfo(() => {
- success()
- })
- })
- }
- //问题反馈
- questionBack(des: string, createBy: string) {
- yTRequest.post<null, reqString>(`/api/${this.productName}/question/saveQuestion`, {
- 'backQuestion': des,
- 'createBy': createBy,
- 'createTime': formatDate(new Date()),
- })
- .then(() => {
- IBestToast.show("反馈成功")
- yTRouter.routerBack()
- })
- .catch((e: Error) => {
- YTLog.error(e)
- })
- }
- }
- export const yTRequest = new YtRequest()
|