request.js 2.63 KB
/**
 * store 请求层:@uj/api-core 的客户端工厂。
 *
 * 一个 createRopClient({配置}) 直接拿到 client;平台 / URL / 签名 / 拦截器都由 api-core 负责,
 * 本文件只传域名、凭据、会话与登录回调。
 * public API 与旧壳一致:get/post/request(params, returnAll, requestPath),
 * params 含 method,requestPath 对应 hostType(scrm/dj,缺省 scrm)。
 */
// 小程序走主入口具名导出(构建 npm 不保证解析 exports 子路径);web/Node 可用 @uj/api-core/Request。
import { createRopClient } from '@uj/api-core'
import { sign, domain, djSecretKey, pathEnum, secretKey } from './http.js'
import { getSessionId } from '~/utils/cache/storageApi'
import network from '~/utils/network'

const client = createRopClient({
  hosts: { scrm: domain.scrm, dj: domain.dj, merchant: domain.merchant },
  pathEnum,
  secretKey,
  djSecretKey,
  // 本 app 的签名实现(字节级对齐旧壳):直接传函数,工厂内部包成签名策略。
  signature: sign,
  defaultCredential: {
    appKey: '48e5e13229b82c1b4e6e8c96151f0637',
    secret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b',
  },
  session: { sessionId: () => getSessionId() || '' },
  loginReplay: true,
  // 网络不可用:与旧壳一致——静默返回(不 reject、不 toast),由调用方自行兜底。
  beforeRequest: async () => {
    const type = await network.getNetworkType()
    if (type == 'none') return { abort: true, value: undefined }
  },
  onLoginRequired: (_code, { body }) => {
    wx.$storage.rm('sessionId')
    wx.$storage.rm('userInfo')
    wx.$storage.rm('subMerchant')
    const thisPage = wx.$router.getPageInstance()
    const autoLoginObject = wx.$storage.get('auto_login_object')
    // 旧壳特例:已在登录 loading 页时,直接 resolve 完整信封,不再跳转。
    if (thisPage.route == 'login/loading/loading') return { resolve: body }
    if (autoLoginObject) wx.$router.reLaunch('login.loading')
    else wx.$router.reLaunch('login.index')
  },
})

const call = (params, returnAll = false, requestPath = 'scrm') =>
  client.post(params.method, params, {
    hostType: requestPath,
    returnAll,
    // apiProjectName 是旧壳用来覆盖项目名的参数(api/index.js、output.js、login 用到)。
    projectName: params.apiProjectName,
  })

const api = {
  get: (params, returnAll = false, requestPath = 'scrm') => call(params, returnAll, requestPath),
  post: (params, returnAll = false, requestPath = 'scrm') => call(params, returnAll, requestPath),
  request: (params, returnAll = false, requestPath = 'scrm') => call(params, returnAll, requestPath),
}

export default api