/** * @author xiaoping * @email edwardhjp@gmail.com * @create date 2018-07-11 03:33:14 * @modify date 2018-07-11 03:33:14 * @desc [mtop通用封装] */ // import WindVane from '@ali/lib-windvane' import WindVane from '../../../../lib/windvane.common.js' // import Mtop from '@ali/lib-mtop/build/mtop.common' import Mtop from '../../../../lib/mtop.common.js' import { get } from 'jsonuri' interface RequestOptions { api?: string v?: string data?: any, absAPI?: any } function __getLocalStorageItem (key): string | undefined { return get(window, `/localStorage/${key}`) } // 统一处理未登录 function __goLogin() { window.location.href = `https://login.m.taobao.com/login.htm?redirectURL=${encodeURIComponent(window.location.href)}` } function mtopNativeRequest (options: RequestOptions = {}): Promise { let params = { ...{ version: '1.0', method: 'get', bizParams: options.data }, ...options } params.version = options.v || params.version return new Promise((resolve, reject) => { WindVane.call('Mtop', 'request', params, resolve, reject) }) } // 用户信息更改ls的__authInfo,mtop环境更改ls的__mtopEnv function mtopH5Request (options: RequestOptions): Promise { let params = { ...{ // 通用参数 // api: '', // 必须 v: '1.0', // 必须 // data: {}, // 必须(注意1) // appKey: '12574478', // 非必须,默认不需要传 ecode: 0, // 必须(注意2) type: 'GET', // 非必须。请求类型(GET/POST),默认是GET dataType: 'jsonp', // 非必须。数据类型(jsonp/originaljsonp/json),默认jsonp timeout: 20000 // 非必须。接口超时设置,默认为20000ms }, ...options } // 模拟authInfo const authInfo = __getLocalStorageItem('__authInfo') if (authInfo) { params.data.authInfo = authInfo } // 模拟mtop环境 const mtopEnv = __getLocalStorageItem('__mtopEnv') if (mtopEnv) { // 是否是 api 为绝对值,如果是,不改变 api 地址 if (params.absAPI) { delete params.absAPI } else { params.api = params.api + mtopEnv } const lib = window['lib'] if (lib && /pre/.test(mtopEnv)) { lib.mtop.config.subDomain = 'wapa' lib.mtop.config.mainDomain = 'taobao.com' lib.mtop.config.prefix = 'h5api' } } return new Promise((resolve, reject) => { Mtop.request(params) .then(res => resolve(res.data)) .catch(err => { if (err.retType === 2) { __goLogin() } reject(err) }) }) } export function mtopv2 (options: RequestOptions): Promise { if (WindVane.isAvailable) { return mtopNativeRequest(options) } return mtopH5Request(options) } // 根据一定规则区分业务成功和失败,formatRes: { success: true, data: {} } export function mtopFormat (options: RequestOptions, format?: Function | undefined): Promise { if (!format) return mtopv2(options) return new Promise((resolve, reject) => { mtopv2(options) .then(res => { if (res.success) { const formatRes = format(res) || {} resolve(formatRes) } else { reject(res) } }) .catch(err => { reject(err) }) }) }