fn.js 3.33 KB
/*
 * @Date: 2022-05-18 22:56:08
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2024-01-25 10:03:20
 * @FilePath: /xysBooking/src/api/fn.js
 * @Description: API 统一返回处理与 GET/POST 统一封装
 */
import axios from '@/utils/axios';
import { showFailToast, showToast } from 'vant';
import qs from 'Qs'

/**
 * 统一处理后端接口返回
 * - 约定后端返回结构:{ code, data, msg, show }
 * - code === 1 视为成功,原样返回 res.data
 * - 失败时根据 show 决定是否弹出 Toast
 * @param {Promise<import('axios').AxiosResponse>} api axios 请求 Promise
 * @returns {Promise<Object|false>} 成功返回后端对象,失败返回 false
 */
export const fn = (api) => {
  return api
    .then(res => {
      if (res.data.code === 1) {
        return res.data || true;
      } else {
        // tslint:disable-next-line: no-console
        console.warn(res.data.show);
        if (res.data.show === false) return false;
        showToast(res.data.msg);
        return false;
      }
    })
    .catch(err => {
      // tslint:disable-next-line: no-console
      console.error(err);
      return false;
    })
    .finally(() => { // 最终执行
    })
}

/**
 * 七牛上传接口返回处理
 * - 七牛成功时常见表现为 res.statusText === 'OK'
 * - 与业务接口不同,失败提示使用 showFailToast
 * @param {Promise<import('axios').AxiosResponse>} api axios 请求 Promise
 * @returns {Promise<Object|false>} 成功返回 res.data,失败返回 false
 */
export const uploadFn = (api) => {
  return api
    .then(res => {
      if (res.statusText === 'OK') {
        return res.data || true;
      } else {
        // tslint:disable-next-line: no-console
        console.warn(res);
        if (!res.data.show) return false;
        showFailToast(res.data.msg);
        return false;
      }
    })
    .catch(err => {
      // tslint:disable-next-line: no-console
      console.error(err);
      return false;
    })
}

/**
 * 统一封装 GET/POST 的传参形式
 * - get:以 { params } 形式传递查询参数
 * - post:以 JSON 形式传递 body
 * - stringifyPost:以 x-www-form-urlencoded 形式传递 body(兼容部分 PHP 接口)
 */
export const fetch = {
  /**
   * GET 请求封装
   * @param {string} api 接口地址
   * @param {Object} params 查询参数
   * @returns {Promise<import('axios').AxiosResponse>} axios Promise
   */
  get: function (api, params) {
    return axios.get(api, { params })
  },
  /**
   * POST 请求封装(JSON body)
   * @param {string} api 接口地址
   * @param {Object} params 请求体
   * @returns {Promise<import('axios').AxiosResponse>} axios Promise
   */
  post: function (api, params) {
    return axios.post(api, params)
  },
  /**
   * POST 请求封装(urlencoded body)
   * @param {string} api 接口地址
   * @param {Object} params 请求体
   * @returns {Promise<import('axios').AxiosResponse>} axios Promise
   */
  stringifyPost: function (api, params) {
    return axios.post(api, qs.stringify(params))
  },
  /**
   * 透传 POST(用于七牛等第三方上传)
   * @param {string} url 完整 URL
   * @param {any} data body 数据
   * @param {Object} config axios 配置
   * @returns {Promise<import('axios').AxiosResponse>} axios Promise
   */
  basePost: function (url, data, config) {
    return axios.post(url, data, config)
  }
}