request.uts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { env, TIMEOUT } from '@/common/env.uts'
  2. export type ApiResponse<T> = {
  3. code : number
  4. message : string
  5. data : T | null
  6. }
  7. export type RequestOptions = {
  8. url : string
  9. method ?: string
  10. data ?: UTSJSONObject | null
  11. header ?: UTSJSONObject | null
  12. showLoading ?: boolean
  13. }
  14. function getToken() : string {
  15. const token = uni.getStorageSync('token')
  16. if (token == null) return ''
  17. return token as string
  18. }
  19. export function request<T>(options : RequestOptions) : Promise<T> {
  20. return new Promise<T>((resolve, reject) => {
  21. const header : UTSJSONObject = options.header ?? {}
  22. header['Content-Type'] = 'application/json'
  23. const token = getToken()
  24. if (token.length > 0) {
  25. header['Authorization'] = 'Bearer ' + token
  26. }
  27. uni.request({
  28. url: env.baseUrl + options.url,
  29. method: options.method ?? 'GET',
  30. data: options.data,
  31. header: header,
  32. timeout: TIMEOUT,
  33. success: (res) => {
  34. const statusCode = res.statusCode
  35. if (statusCode >= 200 && statusCode < 300) {
  36. const body = res.data as UTSJSONObject
  37. const code = body.getNumber('code')
  38. if (code != null && code == 200) {
  39. resolve(body.get('data') as T)
  40. } else {
  41. const msg = body.getString('message') ?? '请求失败'
  42. uni.showToast({ title: msg, icon: 'none' })
  43. reject(new Error(msg))
  44. }
  45. } else {
  46. const msg = '网络错误 ' + statusCode
  47. uni.showToast({ title: msg, icon: 'none' })
  48. reject(new Error(msg))
  49. }
  50. },
  51. fail: (err) => {
  52. const msg = err.errMsg ?? '请求失败'
  53. uni.showToast({ title: msg, icon: 'none' })
  54. reject(new Error(msg))
  55. }
  56. })
  57. })
  58. }
  59. export function get<T>(url : string, data ?: UTSJSONObject | null) : Promise<T> {
  60. return request<T>({ url: url, method: 'GET', data: data })
  61. }
  62. export function post<T>(url : string, data ?: UTSJSONObject | null) : Promise<T> {
  63. return request<T>({ url: url, method: 'POST', data: data })
  64. }