Skip to content

Commit 4b22094

Browse files
committed
fix(sdk-middleware-http): try json parse with catch block
1 parent a72fd84 commit 4b22094

File tree

2 files changed

+45
-3
lines changed

2 files changed

+45
-3
lines changed

packages/sdk-middleware-http/src/http.js

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -68,13 +68,18 @@ export default function createHttpMiddleware({
6868
} = {},
6969
fetch: fetcher,
7070
abortController: _abortController,
71-
getAbortController
71+
getAbortController,
7272
}: HttpMiddlewareOptions): Middleware {
7373
if (!fetcher && typeof fetch === 'undefined')
7474
throw new Error(
7575
'`fetch` is not available. Please pass in `fetch` as an option or have it globally available.'
7676
)
77-
if (timeout && !getAbortController && !_abortController && typeof AbortController === 'undefined')
77+
if (
78+
timeout &&
79+
!getAbortController &&
80+
!_abortController &&
81+
typeof AbortController === 'undefined'
82+
)
7883
throw new Error(
7984
'`AbortController` is not available. Please pass in `getAbortController` as an option or have AbortController globally available when using timeout.'
8085
)
@@ -148,9 +153,17 @@ export default function createHttpMiddleware({
148153
}
149154

150155
res.text().then((result: Object) => {
156+
let resBody
157+
158+
try {
159+
resBody = result.length > 0 ? JSON.parse(result) : {}
160+
} catch (err) {
161+
resBody = result
162+
}
163+
151164
const parsedResponse: Object = {
152165
...response,
153-
body: result.length > 0 ? JSON.parse(result) : {},
166+
body: resBody,
154167
statusCode: res.status,
155168
}
156169

packages/sdk-middleware-http/test/http.spec.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,35 @@ describe('Http', () => {
7070
httpMiddleware(next)(request, response)
7171
}))
7272

73+
test('execute a get request which give not json response', () =>
74+
new Promise((resolve, reject) => {
75+
const request = createTestRequest({
76+
uri: '/foo/bar',
77+
})
78+
const response = { resolve, reject }
79+
const next = (req, res) => {
80+
expect(res).toEqual({
81+
...response,
82+
body: 'not json response',
83+
statusCode: 200,
84+
})
85+
resolve()
86+
}
87+
// Use default options
88+
const httpMiddleware = createHttpMiddleware({
89+
host: testHost,
90+
fetch,
91+
})
92+
nock(testHost)
93+
.defaultReplyHeaders({
94+
'Content-Type': 'application/json',
95+
})
96+
.get('/foo/bar')
97+
.reply(200, 'not json response')
98+
99+
httpMiddleware(next)(request, response)
100+
}))
101+
73102
test('execute a get request with timeout (success)', () =>
74103
new Promise((resolve, reject) => {
75104
const request = createTestRequest({

0 commit comments

Comments
 (0)