parse.mjs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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);
  13. }
  14. return Stream.fromSSEResponse(response, props.controller);
  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 contentLength = response.headers.get('content-length');
  28. if (contentLength === '0') {
  29. // if there is no content we can't do anything
  30. return undefined;
  31. }
  32. const json = await response.json();
  33. return addRequestID(json, response);
  34. }
  35. const text = await response.text();
  36. return text;
  37. })();
  38. loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({
  39. retryOfRequestLogID,
  40. url: response.url,
  41. status: response.status,
  42. body,
  43. durationMs: Date.now() - startTime,
  44. }));
  45. return body;
  46. }
  47. export function addRequestID(value, response) {
  48. if (!value || typeof value !== 'object' || Array.isArray(value)) {
  49. return value;
  50. }
  51. return Object.defineProperty(value, '_request_id', {
  52. value: response.headers.get('request-id'),
  53. enumerable: false,
  54. });
  55. }
  56. //# sourceMappingURL=parse.mjs.map