import isPlainObject from 'lodash/isPlainObject' import compatAxios from '@sdp.nd/request/lib/compat' import Request from '@sdp.nd/request' import buildURL from '@sdp.nd/util/lib/build-url' import headerP2p from '@sdp.nd/util/lib/header-p2p' import One from '..' /** * 初始化 Request * @requires Storage * @requires UC */ export default function pluginRequest ($: One) { // 向外暴露类 $.Request = Request const { UC, options: { env, combine, request, axiosCompatible, headerP2P } } = $ if ($.__use_smartcan) { // 直接使用 RESTDAO,无需关注跨域与请求合并 $.request = new Request(request) return } // 聚合网关配置处理 let _combine = combine if (_combine) { if (!isPlainObject(_combine)) { _combine = {} } if (!_combine.env) { _combine.env = env } } $.request = new Request({ combine: _combine, ...request }) if (axiosCompatible) { // compat.compatAxios($.request) // 怀疑原写法有问题 compatAxios($.request) } // const AUTH_INVALID_TIMESTAMP = 'UC/AUTH_INVALID_TIMESTAMP' // iReqPre -> iReqGlobal -> iReq.pre -> iReq.post -> iReqPost // .........................^^^^^^^^......................... $.request.intercept(async config => { const { url: _url, method, params, paramsSerializer, headers = {}, ...restConfig } = config // 需要 encode,顺便把 params 带上 const url = buildURL(_url, params, paramsSerializer).replace(/@/g, '%40') const hasToken = await $._checkToken() // 如果存在 token if (hasToken) { try { // 则设置请求头 Authorization headers.Authorization = await UC.getAuthHeaderAsync({url, method}) } catch (error) { console.error(error) } } // x-sdp-fp if ((window as any).getSdpFp) { headers['x-sdp-fp'] = (window as any).getSdpFp() } // params 已经并入 url,此处不再传下去 return Object.assign(restConfig, { url, method, // 设置通用的请求头:sdp-app-id、sdp-migrated 等。 headres 需要放在 assign 后面,有业务方订制 headers: Object.assign({}, getStaticHeaders($), headerP2P === false ? null : headerP2p(), headers) }) }) } // 无需异步 export function asyncPluginRequest ($: One) { pluginRequest($) } /** * 获取静态请求头 * @param {object} $ one */ function getStaticHeaders ($: One): object { const { storage, options: { headerKeys } } = $ return headerKeys // 使用自定义 headerKeys ? headerKeys.reduce((obj, key) => { const value = key === 'Accept-Language' ? $.getLanguage() : storage.get(key) if (value !== '' && value !== undefined && value !== null) { return Object.assign(obj, { [key]: value }) } return obj }, {}) // 使用默认的租户信息与语言 : { ...$.getTenant(), 'Accept-Language': $.getLanguage() } }