From 94e0c31065ef53146fef819bf321edaa069c378a Mon Sep 17 00:00:00 2001 From: Jovi De Croock Date: Tue, 14 Nov 2023 21:51:01 +0100 Subject: [PATCH] chore(core): try to parse a text/plain content-type response as json (#3430) --- .changeset/silver-planets-sniff.md | 5 +++++ packages/core/src/internal/fetchSource.ts | 19 ++++++++++++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 .changeset/silver-planets-sniff.md diff --git a/.changeset/silver-planets-sniff.md b/.changeset/silver-planets-sniff.md new file mode 100644 index 0000000000..0197a1b31e --- /dev/null +++ b/.changeset/silver-planets-sniff.md @@ -0,0 +1,5 @@ +--- +'@urql/core': minor +--- + +Try to parse `text/plain` content-type as JSON before bailing out with an error. diff --git a/packages/core/src/internal/fetchSource.ts b/packages/core/src/internal/fetchSource.ts index a29d46f297..2b4f0a28fa 100644 --- a/packages/core/src/internal/fetchSource.ts +++ b/packages/core/src/internal/fetchSource.ts @@ -147,6 +147,23 @@ async function* parseMultipartMixed( } } +async function* parseMaybeJSON( + response: Response +): AsyncIterableIterator { + const text = await response.text(); + try { + const result = JSON.parse(text); + if (process.env.NODE_ENV !== 'production') { + console.warn( + `Found response with content-type "text/plain" but it had a valid "application/json" response.` + ); + } + yield result; + } catch (e) { + throw new Error(text); + } +} + async function* fetchOperation( operation: Operation, url: string, @@ -172,7 +189,7 @@ async function* fetchOperation( } else if (!/text\//i.test(contentType)) { results = parseJSON(response); } else { - throw new Error(await response.text()); + results = parseMaybeJSON(response); } let pending: ExecutionResult['pending'];