http.js 4.03 KB
/**
 * points 请求层:@uj/api-core 的客户端工厂。
 *
 * 一个 createClient({ kind: 'rop', 配置}) 直接拿到 client;平台 / URL 拼装 / 签名 /
 * 拦截器(业务码归一 / 登录跳转 / loading / toast)由 api-core 负责。
 *
 * public API 与旧壳一致:get/post/request(RequestMethods, params, returnAll)、
 * fetch(method, data, returnAll=true)、reportTrack(params)、wx_request({...})。
 * 另外补上 common.js 调用了但旧壳从未定义的 getMock()(配置中心拉取)。
 *
 * 与另外三个 app 的差异用「语义化参数」表达:
 *   · SHA1 不摊平 params → 内置签名策略 'rop-sha1'(与旧 getData 逐字节一致)
 *   · 单一域名 / merchantId 头三级回退 → hosts、getMerchantId
 *   · 业务失败 / 登录失效后 Promise 挂起 → loginReplay
 */
// 小程序走主入口具名导出(构建 npm 不保证解析 exports 子路径);web/Node 可用 @uj/api-core/Request。
import { createClient } from '@uj/api-core'
import {
  defaultMerchantId,
  secretKey,
  pathEnum,
  domain,
  env,
} from '../env/index'

const DEFAULT_CRED = {
  appKey: '48e5e13229b82c1b4e6e8c96151f0637',
  secret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b',
}

const client = createClient({
  kind: 'rop',
  hosts: { scrm: domain },
  pathEnum,
  secretKey,
  defaultCredential: DEFAULT_CRED,
  signature: 'rop-sha1',
  session: {
    sessionId: () => (wx.p.storage.get() || {}).sessionId || '',
  },
  getMerchantId: () => {
    const info = wx.p.storage.get('merchant_info') || {}
    return wx.$merchant_id || info.merchantId || defaultMerchantId
  },
  loginReplay: true,
  onLoginRequired: () => {
    // 旧壳:hideLoading → 清会话 → redirectTo 登录页。
    wx.hideLoading?.()
    wx.p.storage.rm('sessionId')
    wx.p.isLogin = false
    wx.p.storage.rm('userInfo')
    wx.p.router.redirectTo('/pages/Login/Login')
  },
  // 传输失败:改写提示文案(旧壳 fail 分支)。
  onTransportError: (error) => {
    // 旧壳 fail 分支会先关掉 loading。
    wx.hideLoading?.()
    const message = typeof error === 'string'
      ? error
      : (error && (error.errMsg || error.message)) || JSON.stringify(error) || '系统异常'
    console.error('[request fail]', error)
    return { message }
  },
})

const call = (params, returnAll = false, httpMethod = 'POST') =>
  client.request({
    url: params.method,
    method: httpMethod,
    data: params,
    returnAll,
    // projectName 覆盖项目名、noSignAttr 从签名原文排除,旧壳都是从 params 里摘出来用的。
    projectName: params.projectName,
    noSignAttr: params.noSignAttr,
    headers: httpMethod === 'GET' ? { 'Cache-Control': 'no-cache' } : undefined,
  })

const api = {
  get: (params, returnAll = false) => call(params, returnAll, 'GET'),
  post: (params, returnAll = false) => call(params, returnAll, 'POST'),
  request: (httpMethod, params, returnAll = false) => call(params, returnAll, httpMethod),
  // 注意:旧壳 fetch 的 returnAll 默认 true,返回完整信封 { code, data, message }。
  fetch: (method, data = {}, returnAll = true) => call({ method, ...data }, returnAll, 'POST'),
  reportTrack: (params) => call(params, true, 'POST'),
  // 裸 wx.request:配置中心 / 非 ROP 接口,原样保留(不进签名、不进业务码归一)。
  wx_request({
    url,
    method = 'GET',
    data = {},
    header = {},
    dataType = 'json',
    responseType = 'text',
  }) {
    return new Promise((resolve) => {
      wx.request({
        url, data, method, header, dataType, responseType,
        success(response) { resolve(response.data) },
      })
    })
  },
  // 兼容 common.js 的 http.getMock():旧壳缺此方法(调用会 TypeError),
  // 这里与 system.js 的 getConfigData 同源,走同一份配置中心数据。
  getMock() {
    const configModule = 'mini-points-mall'
    const configUrl = `https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=${configModule}&env=${env}`
    return api.wx_request({ url: configUrl })
  },
}

export default api