Skip to content

Commit

Permalink
fix(wx): onDownloadProgress
Browse files Browse the repository at this point in the history
  • Loading branch information
07akioni committed Jul 25, 2024
1 parent d22f564 commit ce4e6cf
Show file tree
Hide file tree
Showing 13 changed files with 633 additions and 59 deletions.
22 changes: 16 additions & 6 deletions demos/wx/pages/index/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const { lyla } = require('@lylajs/wx')
// copy @lylajs/wx/dist to here
const { lyla } = require('./lyla')

// index.js
Page({
Expand All @@ -7,16 +8,25 @@ Page({
},
onShow() {
lyla
.get('https://randomuser.me/api/', {
.post('https://chat.deepseek.com/api/v0/chat/completions', {
headers: {
foo: 'bar'
Authorization: 'Bearer xxx'
},
json: {
message: 'Hello',
stream: true,
model_preference: null,
model_class: 'deepseek_chat',
temperature: 0
},
onDownloadProgress({ detail }) {
console.log('!!!1', detail.responseText)
}
})
.then((resp) => {
console.log(resp.detail)
console.log('resp', resp.headers, resp.body, resp.json)
console.log('!!!2', resp.body)
this.setData({
respBody: JSON.stringify(resp.json)
respBody: resp.body
})
})
}
Expand Down
2 changes: 1 addition & 1 deletion demos/wx/project.config.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"appid": "touristappid",
"appid": "wx1a2d50c6c8b5a3d3",
"compileType": "miniprogram",
"libVersion": "2.17.0",
"packOptions": {
Expand Down
6 changes: 4 additions & 2 deletions demos/wx/project.private.config.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
{
"projectname": "wx",
"setting": {
"compileHotReLoad": true
"compileHotReLoad": true,
"urlCheck": false
},
"description": "项目私有配置文件。此文件中的内容将覆盖 project.config.json 中的相同字段。项目的改动优先同步到此文件中。详见文档:https://developers.weixin.qq.com/miniprogram/dev/devtools/projectconfig.html"
"description": "项目私有配置文件。此文件中的内容将覆盖 project.config.json 中的相同字段。项目的改动优先同步到此文件中。详见文档:https://developers.weixin.qq.com/miniprogram/dev/devtools/projectconfig.html",
"libVersion": "3.5.0"
}
85 changes: 46 additions & 39 deletions packages/core/src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,7 @@ export function createLyla<C, M extends LylaAdapterMeta>(
}

let hasNetworkError = false
const onHeadersReceived = _options.hooks?.onHeadersReceived
const adapterHandle = adapter({
url,
method,
Expand Down Expand Up @@ -401,47 +402,53 @@ export function createLyla<C, M extends LylaAdapterMeta>(
handleResponseError(networkError)
_reject(networkError)
},
onDownloadProgress: (progress) => {
onDownloadProgress?.({ ...progress, requestOptions: _options })
},
onUploadProgress: (progress) => {
onUploadProgress?.({ ...progress, requestOptions: _options })
},
onHeadersReceived: (_headers, originalRequest) => {
if (aborted) return
if (hasNetworkError) return
if (_options.hooks?.onHeadersReceived) {
const headers = mergeHeaders({}, _headers)
try {
for (const hook of _options.hooks.onHeadersReceived) {
hook(
{ headers, requestOptions: _options, originalRequest },
_customReject
)
onDownloadProgress: onDownloadProgress
? (progress) => {
onDownloadProgress({ ...progress, requestOptions: _options })
}
: undefined,
onUploadProgress: onUploadProgress
? (progress) => {
onUploadProgress({ ...progress, requestOptions: _options })
}
: undefined,
onHeadersReceived: onHeadersReceived
? (_headers, originalRequest) => {
if (aborted) return
if (hasNetworkError) return
if (onHeadersReceived) {
const headers = mergeHeaders({}, _headers)
try {
for (const hook of onHeadersReceived) {
hook(
{ headers, requestOptions: _options, originalRequest },
_customReject
)
}
} catch (error) {
const brokenOnHeadersReceived = defineLylaError<
M,
C,
LylaBrokenOnHeadersReceivedError<C, M>
>(
{
type: LYLA_ERROR.BROKEN_ON_HEADERS_RECEIVED,
message: '`onHeadersReceived` hook throws error',
detail: undefined,
response: undefined,
error,
context: _options.context,
requestOptions: _options
},
undefined
)
handleNonResponseError(brokenOnHeadersReceived)
_reject(brokenOnHeadersReceived)
return
}
}
} catch (error) {
const brokenOnHeadersReceived = defineLylaError<
M,
C,
LylaBrokenOnHeadersReceivedError<C, M>
>(
{
type: LYLA_ERROR.BROKEN_ON_HEADERS_RECEIVED,
message: '`onHeadersReceived` hook throws error',
detail: undefined,
response: undefined,
error,
context: _options.context,
requestOptions: _options
},
undefined
)
handleNonResponseError(brokenOnHeadersReceived)
_reject(brokenOnHeadersReceived)
return
}
}
},
: undefined,
async onResponse(resp, detail) {
if (aborted) return
if (hasNetworkError) return
Expand Down
10 changes: 6 additions & 4 deletions packages/core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,10 +243,12 @@ export interface LylaAdapterOptions<T extends LylaAdapterMeta> {
onDownloadProgress:
| ((progress: Omit<LylaProgress<unknown, T>, 'requestOptions'>) => void)
| undefined
onHeadersReceived(
headers: Record<string, string>,
originalRequest: T['originalRequest']
): void
onHeadersReceived:
| ((
headers: Record<string, string>,
originalRequest: T['originalRequest']
) => void)
| undefined
onResponse(
response: {
body: T['responseBody']
Expand Down
37 changes: 34 additions & 3 deletions packages/wx/src/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type {
WxRequestMethod,
WxRequestTask
} from './types'
import { arrayBufferToString } from './utils'

declare const wx: {
request: WxRequest
Expand All @@ -21,7 +22,7 @@ export interface LylaAdapterMeta extends LylaCoreAdapterMeta {
responseDetail: ResponseDetail
responseType: 'arraybuffer' | 'text'
requestBody: string | ArrayBuffer
progressDetail: { data: ArrayBuffer }
progressDetail: { data: ArrayBuffer; responseText: string }
originalRequest: WxRequestTask
extraOptions: never
}
Expand All @@ -43,6 +44,8 @@ export const adapter: LylaAdapter<LylaAdapterMeta> = ({
}): {
abort: () => void
} => {
let latestProgressData: Uint8Array | undefined = undefined

const requestTask = wx.request({
url,
method,
Expand All @@ -57,9 +60,19 @@ export const adapter: LylaAdapter<LylaAdapterMeta> = ({
onNetworkError(res)
},
success(res) {
let body: string | ArrayBuffer
if (onDownloadProgress) {
if (responseType === 'arraybuffer') {
body = latestProgressData || new ArrayBuffer(0)
} else {
body = arrayBufferToString(latestProgressData || new ArrayBuffer(0))
}
} else {
body = res.data as string | ArrayBuffer
}
onResponse(
{
body: res.data as string | ArrayBuffer,
body,
status: res.statusCode,
headers: headersKeyToLowerCase(res.header)
},
Expand All @@ -69,8 +82,26 @@ export const adapter: LylaAdapter<LylaAdapterMeta> = ({
})
if (onDownloadProgress) {
requestTask.onChunkReceived((detail) => {
if (!latestProgressData) {
latestProgressData = new Uint8Array([])
}
let mergedProgressData = new Uint8Array(
latestProgressData.byteLength + detail.data.byteLength
)
mergedProgressData.set(latestProgressData, 0)
mergedProgressData.set(
detail.data instanceof Uint8Array
? detail.data
: new Uint8Array(detail.data),
latestProgressData.byteLength
)
latestProgressData = mergedProgressData

onDownloadProgress({
detail,
detail: {
data: detail.data,
responseText: arrayBufferToString(latestProgressData)
},
lengthComputable: false,
loaded: 0,
originalRequest: requestTask,
Expand Down
1 change: 1 addition & 0 deletions packages/wx/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ export type {
} from './reexports'
export { LYLA_ERROR, LylaAbortController } from './reexports'
export { lyla, isLylaError, createLyla } from './instance'
export { arrayBufferToString } from './utils'
1 change: 1 addition & 0 deletions packages/wx/src/utils.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const arrayBufferToString: (buffer: ArrayBuffer) => string
Loading

0 comments on commit ce4e6cf

Please sign in to comment.