Skip to content

Commit

Permalink
refactor: add runtime validation of batch requests
Browse files Browse the repository at this point in the history
  • Loading branch information
Keith-CY committed Oct 30, 2023
1 parent 7ba4b97 commit fdd88dc
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
4 changes: 4 additions & 0 deletions packages/neuron-wallet/src/utils/ckb-rpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,10 @@ export class LightRPC extends Base {
})
const batchRes = await res.body.json()

if (!Array.isArray(batchRes)) {
return []
}

return batchRes.map((res: any, i: number) => {
if (res.id !== payload[i].id) {
return new IdNotMatchedInBatchException(i, payload[i].id, res.id)
Expand Down
13 changes: 10 additions & 3 deletions packages/neuron-wallet/src/utils/rpc-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,10 @@ export const rpcRequest = async <T = any>(
throw new Error(`indexer request failed with HTTP code ${res.statusCode}`)
}
const body = await res.body.json()
return body?.result as T
if (body !== null && typeof body === 'object' && 'result' in body) {
return body?.result as T
}
return [] as T
}

export const rpcBatchRequest = async (
Expand All @@ -50,8 +53,12 @@ export const rpcBatchRequest = async (
if (res.statusCode !== 200) {
throw new Error(`indexer request failed with HTTP code ${res.statusCode}`)
}
const responseBody: { id: number; error?: any; result: any }[] = await res.body.json()
return responseBody.sort((a, b) => a.id - b.id)
// const responseBody: { id: number; error?: any; result: any }[] = await res.body.json()
const responseBody = await res.body.json()
if (Array.isArray(responseBody) && responseBody.every(i => 'id' in i)) {
return responseBody.sort((a, b) => a.id - b.id)
}
return []
}

export default {
Expand Down

1 comment on commit fdd88dc

@github-actions
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Packaging for test is done in 6687823914

Please sign in to comment.