parse.js 2.3 KB

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