request.uts 9.6 KB
Newer Older
DCloud-yyl's avatar
DCloud-yyl 已提交
1
import http from '@ohos.net.http'
DCloud-yyl's avatar
DCloud-yyl 已提交
2
import buffer from '@ohos.buffer';
DCloud-yyl's avatar
DCloud-yyl 已提交
3 4 5
import {
    isPlainObject,
    Emitter,
DCloud-yyl's avatar
DCloud-yyl 已提交
6
    getCurrentMP,
DCloud-yyl's avatar
DCloud-yyl 已提交
7 8 9 10 11 12 13 14 15 16 17 18 19
} from '@dcloudio/uni-runtime'
import {
    RequestTask as UniRequestTask,
    RequestOptions as UniRequestOptions,
    RequestSuccess as UniRequestSuccess,
    Request
} from '../../interface.uts'
import {
    API_REQUEST,
    RequestApiOptions,
    RequestApiProtocol,
} from '../../protocol.uts'
import {
DCloud-yyl's avatar
DCloud-yyl 已提交
20 21
    getClientCertificate,
    parseUrl,
DCloud-yyl's avatar
DCloud-yyl 已提交
22
} from './utils.uts'
DCloud-yyl's avatar
DCloud-yyl 已提交
23 24
import {
    getCookieSync,
DCloud-yyl's avatar
DCloud-yyl 已提交
25
    setCookieSync,
DCloud-yyl's avatar
DCloud-yyl 已提交
26 27 28 29 30 31 32 33
} from './cookie.uts'

interface IUniRequestEmitter {
    on: (eventName: string, callback: Function) => void
    once: (eventName: string, callback: Function) => void
    off: (eventName: string, callback?: Function | null) => void
    emit: (eventName: string, ...args: (Object | undefined | null)[]) => void
}
DCloud-yyl's avatar
DCloud-yyl 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73

// copy from uni-app-plus/src/service/api/network/request.ts
const cookiesParse = (header: Record<string, string>) => {
    let cookiesArr: string[] = []
    const handleCookiesArr = (header['Set-Cookie'] || header['set-cookie'] || []) as string[]
    for (let i = 0; i < handleCookiesArr.length; i++) {
        if (
            handleCookiesArr[i].indexOf('Expires=') !== -1 ||
            handleCookiesArr[i].indexOf('expires=') !== -1
        ) {
            cookiesArr.push(handleCookiesArr[i].replace(',', ''))
        } else {
            cookiesArr.push(handleCookiesArr[i])
        }
    }
    return cookiesArr
}

interface IRequestTask {
    abort: Function
    onHeadersReceived: Function
    offHeadersReceived: Function
}

class RequestTask implements UniRequestTask {
    private _requestTask: IRequestTask
    constructor(requestTask: IRequestTask) {
        this._requestTask = requestTask
    }
    abort() {
        this._requestTask.abort()
    }
    onHeadersReceived(callback: Function) {
        this._requestTask.onHeadersReceived(callback)
    }
    offHeadersReceived(callback?: Function) {
        this._requestTask.offHeadersReceived(callback)
    }
}

DCloud-yyl's avatar
DCloud-yyl 已提交
74 75 76 77 78 79
/**
 * http.request有5MB响应体大小限制
 * rcp.Session.fetch无响应体大小限制,但是headers、cookies处理不够完善,另外rcp需要从@hms引用,不是openharmony标准库
 * 为突破http.request的限制,现在使用http.requestInStream
 */

DCloud-yyl's avatar
DCloud-yyl 已提交
80 81 82 83
export const request = defineTaskApi<UniRequestOptions<Object>, UniRequestSuccess<Object>, UniRequestTask>(
    API_REQUEST,
    (args: UniRequestOptions<Object>, exec: ApiExecutor<UniRequestSuccess<Object>>) => {
        let { header, method, data, dataType, timeout, url, responseType } = args
DCloud-yyl's avatar
DCloud-yyl 已提交
84 85 86 87
        header = header || {} as ESObject
        if (!header!['Cookie'] && !header!['cookie']) {
            header!['Cookie'] = getCookieSync(url);
        }
DCloud-yyl's avatar
DCloud-yyl 已提交
88 89 90 91 92

        let contentType = ''

        // header
        const headers = {} as Record<string, Object>
DCloud-yyl's avatar
DCloud-yyl 已提交
93 94 95 96 97 98
        const headerRecord = header as Object as Record<string, string>
        const headerKeys = Object.keys(headerRecord)
        for (let i = 0; i < headerKeys.length; i++) {
            const name = headerKeys[i];
            if (name.toLowerCase() === 'content-type') {
                contentType = headerRecord[name] as string
DCloud-yyl's avatar
DCloud-yyl 已提交
99
            }
DCloud-yyl's avatar
DCloud-yyl 已提交
100
            headers[name.toLowerCase()] = headerRecord[name]
DCloud-yyl's avatar
DCloud-yyl 已提交
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
        }

        if (!contentType && method === 'POST') {
            headers['Content-Type'] = 'application/json'
            contentType = 'application/json'
        }

        // url data
        if (method === 'GET' && data && isPlainObject(data)) {
            const dataRecord = data as Record<string, Object>
            const query = Object.keys(dataRecord)
                .map((key) => {
                    return (
                        encodeURIComponent(key) +
                        '=' +
                        encodeURIComponent(dataRecord[key] as string | number | boolean)
                    )
                })
                .join('&')
            url += query ?
                (url.indexOf('?') > -1 ? '&' : '?') + query :
                ''
            data = null
        } else if (
            method !== 'GET' &&
            contentType &&
            contentType.indexOf('application/json') === 0 &&
            isPlainObject(data)
        ) {
            data = JSON.stringify(data)
        } else if (
            method !== 'GET' &&
            contentType &&
            contentType.indexOf('application/x-www-form-urlencoded') === 0 &&
            isPlainObject(data)
        ) {
            const dataRecord = data as Record<string, Object>
            data = Object.keys(dataRecord)
                .map((key) => {
                    return (
                        encodeURIComponent(key) +
                        '=' +
                        encodeURIComponent(dataRecord[key] as number | string | boolean)
                    )
                })
                .join('&')
        }

        const httpRequest = http.createHttp()
DCloud-yyl's avatar
DCloud-yyl 已提交
150
        const mp = getCurrentMP()
DCloud-yyl's avatar
DCloud-yyl 已提交
151 152 153 154 155
        const userAgent = mp.userAgent.fullUserAgent
        if (userAgent && headers && !headers!['User-Agent'] && !headers!['user-agent']) {
            headers!['User-Agent'] = userAgent
        }
        const emitter = new Emitter() as IUniRequestEmitter
DCloud-yyl's avatar
DCloud-yyl 已提交
156 157
        const requestTask: IRequestTask = {
            abort() {
DCloud-yyl's avatar
DCloud-yyl 已提交
158
                emitter.off('headersReceive')
DCloud-yyl's avatar
DCloud-yyl 已提交
159 160 161 162 163 164 165
                httpRequest.destroy()
            },
            onHeadersReceived(callback: Function) {
                emitter.on('headersReceive', callback)
            },
            offHeadersReceived(callback?: Function) {
                emitter.off('headersReceive', callback)
DCloud-yyl's avatar
DCloud-yyl 已提交
166
            }
DCloud-yyl's avatar
DCloud-yyl 已提交
167 168
        }

DCloud-yyl's avatar
DCloud-yyl 已提交
169 170 171 172 173 174 175
        function destroy() {
            emitter.off('headersReceive')
            httpRequest.destroy()
        }
        mp.on('beforeClose', destroy)

        let latestHeaders: Object | null = null
DCloud-yyl's avatar
DCloud-yyl 已提交
176
        let lastUrl = url
DCloud-yyl's avatar
DCloud-yyl 已提交
177 178 179 180
        httpRequest.on('headersReceive', (headers: Object) => {
            const realHeaders = headers as Record<string, string | string[]>
            const setCookieHeader = realHeaders['set-cookie'] || realHeaders['Set-Cookie']
            if (setCookieHeader) {
DCloud-yyl's avatar
DCloud-yyl 已提交
181
                setCookieSync(lastUrl, setCookieHeader as string[])
DCloud-yyl's avatar
DCloud-yyl 已提交
182 183
            }
            latestHeaders = headers
DCloud-yyl's avatar
DCloud-yyl 已提交
184 185 186 187
            const location = realHeaders['location'] || realHeaders['Location']
            if (location) {
                lastUrl = location as string
            }
DCloud-yyl's avatar
DCloud-yyl 已提交
188 189 190 191 192 193 194
            // TODO headersReceive存在bug,暂不支持回调给用户。注意重定向时会多次触发,但是只需要给用户回调最后一次
            // emitter.emit('headersReceive', headers);
        })

        const bufs = [] as buffer.Buffer[]
        httpRequest.on('dataReceive', (data) => {
            bufs.push(buffer.from(data))
DCloud-yyl's avatar
DCloud-yyl 已提交
195
        })
DCloud-yyl's avatar
DCloud-yyl 已提交
196 197

        httpRequest.requestInStream(
DCloud-yyl's avatar
DCloud-yyl 已提交
198 199 200 201 202 203 204
            parseUrl(url),
            {
                header: headers,
                method: (method || 'GET').toUpperCase() as http.RequestMethod, // 仅OPTIONS不支持
                extraData: data || undefined, // 传空字符串会报错
                connectTimeout: timeout ? timeout : undefined, // 不支持仅设置一个timeout
                readTimeout: timeout ? timeout : undefined,
DCloud-yyl's avatar
DCloud-yyl 已提交
205
                clientCert: getClientCertificate(url)
DCloud-yyl's avatar
DCloud-yyl 已提交
206
            } as http.HttpRequestOptions,
DCloud-yyl's avatar
DCloud-yyl 已提交
207
            (err, statusCode) => {
DCloud-yyl's avatar
DCloud-yyl 已提交
208 209 210 211
                if (err) {
                    /**
                     * TODO abort后此处收到如下错误,待确认是否直接将此错误码转为abort错误
                     * {"code":2300023,"message":"Failed writing received data to disk/application"}
DCloud-yyl's avatar
DCloud-yyl 已提交
212
                     *
DCloud-yyl's avatar
DCloud-yyl 已提交
213 214 215 216
                     * reject方法第二个参数可以传errCode,reject(err.message, { errCode: -1 })
                     */
                    exec.reject(err.message)
                } else {
DCloud-yyl's avatar
DCloud-yyl 已提交
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
                    const responseData = buffer.concat(bufs)
                    let data: ArrayBuffer | string | object = ''
                    if (responseType === 'arraybuffer') {
                        data = responseData.buffer
                    } else {
                        data = responseData.toString('utf8')
                        if (dataType === 'json') {
                            try {
                                data = JSON.parse(data)
                            } catch (e) {
                                // 与微信保持一致,不抛出异常
                            }
                        }
                    }
                    const headers = latestHeaders as Record<string, string | string[]>
                    const oldCookies = headers ? (headers['Set-Cookie'] || headers['set-cookie'] || []) as string[] : [] as string[]
                    const cookies = latestHeaders ? cookiesParse(latestHeaders as Record<string, string>) : []
                    let newCookies = oldCookies.join(',')
                    if (newCookies) {
                        if (headers['Set-Cookie']) {
                            headers['Set-Cookie'] = newCookies
                        } else {
                            headers['set-cookie'] = newCookies
DCloud-yyl's avatar
DCloud-yyl 已提交
240 241 242 243
                        }
                    }
                    exec.resolve({
                        data,
DCloud-yyl's avatar
DCloud-yyl 已提交
244 245 246
                        statusCode,
                        header: latestHeaders!,
                        cookies: cookies,
DCloud-yyl's avatar
DCloud-yyl 已提交
247 248 249 250
                    } as UniRequestSuccess<Object>)
                }
                requestTask.offHeadersReceived()
                httpRequest.destroy() // 调用完毕后必须调用destroy方法
DCloud-yyl's avatar
DCloud-yyl 已提交
251
                mp.off('beforeClose', destroy)
DCloud-yyl's avatar
DCloud-yyl 已提交
252 253 254 255 256 257 258
            }
        )
        return new RequestTask(requestTask)
    },
    RequestApiProtocol,
    RequestApiOptions
) as Request<Object>