Skip to content

Commit 5b277d8

Browse files
lr0pbyusukebe
andauthored
fix(client): Fix parseResponse not parsing json in react native (#4399)
* Fix parseResponse not working properly in react native * Run format:fix & lint:fix * add a test --------- Co-authored-by: Yusuke Wada <[email protected]>
1 parent 7f4311c commit 5b277d8

File tree

2 files changed

+31
-2
lines changed

2 files changed

+31
-2
lines changed

src/client/fetch-result-please.ts

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,18 @@ const nullBodyResponses = new Set([101, 204, 205, 304])
1212
* Throwing a structured error if the response is not `ok`. ({@link DetailedError})
1313
*/
1414
export async function fetchRP(fetchRes: Response | Promise<Response>): Promise<any> {
15-
const _fetchRes = (await fetchRes) as unknown as Response & { _data: any }
15+
const _fetchRes = (await fetchRes) as unknown as Response & {
16+
_data: any
17+
/**
18+
* @description BodyInit property from whatwg-fetch polyfill
19+
*
20+
* @link https://github.com/JakeChampion/fetch/blob/main/fetch.js#L238
21+
*/
22+
_bodyInit?: any
23+
}
1624

17-
const hasBody = _fetchRes.body && !nullBodyResponses.has(_fetchRes.status)
25+
const hasBody =
26+
(_fetchRes.body || _fetchRes._bodyInit) && !nullBodyResponses.has(_fetchRes.status)
1827

1928
if (hasBody) {
2029
const responseType = detectResponseType(_fetchRes)

src/client/utils.test.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,4 +335,24 @@ describe('parseResponse', async () => {
335335
type _verify = Expect<Equal<ResultType, { message: string }>>
336336
}),
337337
])
338+
339+
it('should parse json response with _bodyInit when body is undefined', async () => {
340+
const mockFetch = vi.fn().mockResolvedValue({
341+
ok: true,
342+
status: 200,
343+
headers: new Headers({ 'content-type': 'application/json' }),
344+
body: undefined,
345+
_bodyInit: '{"message":"test"}',
346+
json: async () => ({ message: 'test' }),
347+
})
348+
349+
global.fetch = mockFetch
350+
351+
const mockClientResponse = {
352+
$get: mockFetch,
353+
}
354+
355+
const result = await parseResponse(mockClientResponse.$get())
356+
expect(result).toEqual({ message: 'test' })
357+
})
338358
})

0 commit comments

Comments
 (0)