import { Request } from '@gem-mine/request' import { buildURL } from '@sdp.nd/request-adapter-waf' interface Options { transformRequest?: (config: any) => object config?: any adapter?: any [key: string]: any } export default (requestOptions?: Options) => { return function () { this.request = new Request({ name: '_ONE_REQUEST_' }) this.data.set('buildInRequest', true) // 使用内置 @gem-mine/request const defaultConfig = { adapter: requestOptions && requestOptions.adapter, before: async (config) => { if (!config.headers) { config.headers = {} } // auth 处理 if (!config.noAuth && this.uc && this.uc.getToken()) { const { url: _url, method, params, paramsSerializer, headers, ...restConfig } = config const url = buildURL(_url, params, paramsSerializer).replace(/@/g, '%40').replace(/'/g, '%27') headers.Authorization = await this.uc.getAuthHeaderAsync({ url, method }) config = Object.assign({}, restConfig, { url, headers, method }) } // headers 插件处理 if (this.headers) { const commonHeaders = this.headers.get() config.headers = Object.assign({}, commonHeaders, config.headers) } // x-sdp-fp if (typeof window !== 'undefined' && (window as any).getSdpFp) { config.headers['x-sdp-fp'] = (window as any).getSdpFp() } // 自定义参数 if (requestOptions && requestOptions.transformRequest && typeof requestOptions.transformRequest === 'function') { config = await requestOptions.transformRequest(config) } return config }, verify: (data) => { const { status } = data return status >= 200 && status < 300 } } this.request.config(Object.assign({} , defaultConfig, requestOptions && requestOptions.config || {})) } }