parse.mjs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
  2. import { Stream } from "../core/streaming.mjs";
  3. import { formatRequestDetails, loggerFor } from "./utils/log.mjs";
  4. export async function defaultParseResponse(client, props) {
  5. const { response, requestLogID, retryOfRequestLogID, startTime } = props;
  6. const body = await (async () => {
  7. if (props.options.stream) {
  8. loggerFor(client).debug('response', response.status, response.url, response.headers, response.body);
  9. // Note: there is an invariant here that isn't represented in the type system
  10. // that if you set `stream: true` the response type must also be `Stream<T>`
  11. if (props.options.__streamClass) {
  12. return props.options.__streamClass.fromSSEResponse(response, props.controller, client);
  13. }
  14. return Stream.fromSSEResponse(response, props.controller, client);
  15. }
  16. // fetch refuses to read the body when the status code is 204.
  17. if (response.status === 204) {
  18. return null;
  19. }
  20. if (props.options.__binaryResponse) {
  21. return response;
  22. }
  23. const contentType = response.headers.get('content-type');
  24. const mediaType = contentType?.split(';')[0]?.trim();
  25. const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json');
  26. if (isJSON) {
  27. const json = await response.json();
  28. return addRequestID(json, response);
  29. }
  30. const text = await response.text();
  31. return text;
  32. })();
  33. loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({
  34. retryOfRequestLogID,
  35. url: response.url,
  36. status: response.status,
  37. body,
  38. durationMs: Date.now() - startTime,
  39. }));
  40. return body;
  41. }
  42. export function addRequestID(value, response) {
  43. if (!value || typeof value !== 'object' || Array.isArray(value)) {
  44. return value;
  45. }
  46. return Object.defineProperty(value, '_request_id', {
  47. value: response.headers.get('x-request-id'),
  48. enumerable: false,
  49. });
  50. }
  51. //# sourceMappingURL=parse.mjs.map