cloudflare/cloudflare-typescript
Publicmirrored from https://github.com/cloudflare/cloudflare-typescriptAvailable
src/internal/parse.ts
56lines · modecode
| 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. |
| 2 | |
| 3 | import type { FinalRequestOptions } from './request-options'; |
| 4 | import { type BaseCloudflare } from '../client'; |
| 5 | import { formatRequestDetails, loggerFor } from './utils/log'; |
| 6 | |
| 7 | export type APIResponseProps = { |
| 8 | response: Response; |
| 9 | options: FinalRequestOptions; |
| 10 | controller: AbortController; |
| 11 | requestLogID: string; |
| 12 | retryOfRequestLogID: string | undefined; |
| 13 | startTime: number; |
| 14 | }; |
| 15 | |
| 16 | export async function defaultParseResponse<T>(client: BaseCloudflare, props: APIResponseProps): Promise<T> { |
| 17 | const { response, requestLogID, retryOfRequestLogID, startTime } = props; |
| 18 | const body = await (async () => { |
| 19 | // fetch refuses to read the body when the status code is 204. |
| 20 | if (response.status === 204) { |
| 21 | return null as T; |
| 22 | } |
| 23 | |
| 24 | if (props.options.__binaryResponse) { |
| 25 | return response as unknown as T; |
| 26 | } |
| 27 | |
| 28 | const contentType = response.headers.get('content-type'); |
| 29 | const mediaType = contentType?.split(';')[0]?.trim(); |
| 30 | const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json'); |
| 31 | if (isJSON) { |
| 32 | const contentLength = response.headers.get('content-length'); |
| 33 | if (contentLength === '0') { |
| 34 | // if there is no content we can't do anything |
| 35 | return undefined as T; |
| 36 | } |
| 37 | |
| 38 | const json = await response.json(); |
| 39 | return json as T; |
| 40 | } |
| 41 | |
| 42 | const text = await response.text(); |
| 43 | return text as unknown as T; |
| 44 | })(); |
| 45 | loggerFor(client).debug( |
| 46 | `[${requestLogID}] response parsed`, |
| 47 | formatRequestDetails({ |
| 48 | retryOfRequestLogID, |
| 49 | url: response.url, |
| 50 | status: response.status, |
| 51 | body, |
| 52 | durationMs: Date.now() - startTime, |
| 53 | }), |
| 54 | ); |
| 55 | return body; |
| 56 | } |
| 57 | |