| 41 | ]); |
| 42 | |
| 43 | export async function parseResponse( |
| 44 | res: Response, |
| 45 | { expectingOk = true, format = 'text', apiName = '' }, |
| 46 | ) { |
| 47 | let body; |
| 48 | try { |
| 49 | const formatter = responseFormatters.get(format, false); |
| 50 | if (!formatter) { |
| 51 | throw new Error(`${format} is not a supported response format.`); |
| 52 | } |
| 53 | body = await formatter(res); |
| 54 | } catch (err) { |
| 55 | throw new APIError(err.message, res.status, apiName); |
| 56 | } |
| 57 | if (expectingOk && !res.ok) { |
| 58 | const isJSON = format === 'json'; |
| 59 | const message = isJSON ? body.message || body.msg || body.error?.message : body; |
| 60 | throw new APIError(isJSON && message ? message : body, res.status, apiName); |
| 61 | } |
| 62 | return body; |
| 63 | } |
| 64 | |
| 65 | export function responseParser(options: { |
| 66 | expectingOk?: boolean; |