fetch-result-please.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // src/client/fetch-result-please.ts
  2. var nullBodyResponses = /* @__PURE__ */ new Set([101, 204, 205, 304]);
  3. async function fetchRP(fetchRes) {
  4. const _fetchRes = await fetchRes;
  5. const hasBody = (_fetchRes.body || _fetchRes._bodyInit) && !nullBodyResponses.has(_fetchRes.status);
  6. if (hasBody) {
  7. const responseType = detectResponseType(_fetchRes);
  8. _fetchRes._data = await _fetchRes[responseType]();
  9. }
  10. if (!_fetchRes.ok) {
  11. throw new DetailedError(`${_fetchRes.status} ${_fetchRes.statusText}`, {
  12. statusCode: _fetchRes?.status,
  13. detail: {
  14. data: _fetchRes?._data,
  15. statusText: _fetchRes?.statusText
  16. }
  17. });
  18. }
  19. return _fetchRes._data;
  20. }
  21. var DetailedError = class extends Error {
  22. /**
  23. * Additional `message` that will be logged AND returned to client
  24. */
  25. detail;
  26. /**
  27. * Additional `code` that will be logged AND returned to client
  28. */
  29. code;
  30. /**
  31. * Additional value that will be logged AND NOT returned to client
  32. */
  33. log;
  34. /**
  35. * Optionally set the status code to return, in a web server context
  36. */
  37. statusCode;
  38. constructor(message, options = {}) {
  39. super(message);
  40. this.name = "DetailedError";
  41. this.log = options.log;
  42. this.detail = options.detail;
  43. this.code = options.code;
  44. this.statusCode = options.statusCode;
  45. }
  46. };
  47. var jsonRegex = /^application\/(?:[\w!#$%&*.^`~-]*\+)?json(?:;.+)?$/i;
  48. function detectResponseType(response) {
  49. const _contentType = response.headers.get("content-type");
  50. if (!_contentType) {
  51. return "text";
  52. }
  53. const contentType = _contentType.split(";").shift();
  54. if (jsonRegex.test(contentType)) {
  55. return "json";
  56. }
  57. return "text";
  58. }
  59. export {
  60. DetailedError,
  61. fetchRP
  62. };