Skip to content

Commit d815529

Browse files
committed
Allow for null JSON bodies to flow through to afterFetch middleware
1 parent 36e81aa commit d815529

File tree

1 file changed

+29
-18
lines changed

1 file changed

+29
-18
lines changed

src/request.ts

Lines changed: 29 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -118,17 +118,20 @@ export class Request {
118118
response: Response,
119119
requestOptions: RequestInit
120120
) {
121-
let wasDelete =
122-
requestOptions.method === "DELETE" &&
123-
[204, 200].indexOf(response.status) > -1
124-
if (wasDelete) return
125-
126-
let json
127-
try {
128-
json = await response.clone().json()
129-
} catch (e) {
130-
if (response.status === 202) return
131-
throw new ResponseError(response, "invalid json", e)
121+
const possiblyEmptyResponseStatuses = [202, 204]
122+
const possiblyEmpty =
123+
possiblyEmptyResponseStatuses.indexOf(response.status) > -1
124+
125+
let json = null
126+
127+
if (204 !== response.status) {
128+
try {
129+
json = await response.clone().json()
130+
} catch (e) {
131+
if (!possiblyEmpty) {
132+
throw new ResponseError(response, "invalid json", e)
133+
}
134+
}
132135
}
133136

134137
try {
@@ -144,13 +147,21 @@ export class Request {
144147

145148
if (response.status >= 500) {
146149
throw new ResponseError(response, "Server Error")
147-
// Allow 422 since we specially handle validation errors
148-
} else if (response.status !== 422 && json.data === undefined) {
149-
if (response.status === 404) {
150-
throw new ResponseError(response, "record not found")
151-
} else {
152-
// Bad JSON, for instance an errors payload
153-
throw new ResponseError(response, "invalid json")
150+
}
151+
152+
// Allow 422 since we specially handle validation errors
153+
if (response.status !== 422) {
154+
if (
155+
(json === null ||
156+
(json.data === undefined && json.meta === undefined)) &&
157+
!possiblyEmpty
158+
) {
159+
if (response.status === 404) {
160+
throw new ResponseError(response, "record not found")
161+
} else {
162+
// Bad JSON, for instance an errors payload
163+
throw new ResponseError(response, "invalid json")
164+
}
154165
}
155166
}
156167

0 commit comments

Comments
 (0)