import { constants } from '@cloudbase/utilities' import { COMPONENT_NAME } from '../constants' import { serializeRequestBody } from './index' import { t } from '..' const { getSdkName, ERRORS } = constants interface IRequestPorps { url: string data?: string | object | ArrayBuffer header?: Record timeout?: number method?: string dataType?: 'json' | string responseType?: 'text' | 'arrayBuffer' mode?: 'cors' | 'no-cors' | 'same-origin' } /** * 封装对齐 wx.request */ export async function request({ url, method = 'GET', header = {}, data, timeout = 60000, dataType = 'json', responseType = 'text', mode, }: IRequestPorps) { const headers = { ...header } data = serializeRequestBody(headers, data) const abortController = new AbortController() let done = false return Promise.race([ new Promise((_, reject) => { setTimeout(() => { const error = new Error(t('请求超时')) ;(error as any).code = 'SERVER_TIMEOUT' if (!done) { abortController.abort?.() } reject(error) }, timeout) }), fetch(url, { method, headers, body: data as any, signal: abortController.signal, mode, }).then( (response) => { done = true if (responseType === 'arrayBuffer') { return response.arrayBuffer() } if (dataType === 'json') { try { return response.json() } catch (e) { throw new Error(`[${getSdkName()}][${ERRORS.INVALID_PARAMS}][${COMPONENT_NAME}.callContainer] response data must be json`,) } } return response.text() }, (e) => { done = true throw e }, ), ]) }