From 729bb3c7ba897661350480a1232dc430e74e4283 Mon Sep 17 00:00:00 2001 From: Mikey Lemmon Date: Fri, 27 May 2022 22:12:41 +1200 Subject: [PATCH] Guard access of response.type to support Cloudflare Workers Fetch responses in Cloudflare Workers currently throw an error on access of the "type" property[^1][^2]. This commit guards access of the type property with a try/catch so that twirp clients can be used inside of Cloudflare Workers. [^1]: https://developers.cloudflare.com/workers/runtime-apis/response/#properties [^2]: https://github.com/cloudflare/miniflare/blob/72f046e/packages/core/src/standards/http.ts#L646 --- packages/twirp-transport/src/twirp-transport.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/twirp-transport/src/twirp-transport.ts b/packages/twirp-transport/src/twirp-transport.ts index bb3376b3..c3e0ee15 100644 --- a/packages/twirp-transport/src/twirp-transport.ts +++ b/packages/twirp-transport/src/twirp-transport.ts @@ -58,7 +58,13 @@ export class TwirpFetchTransport implements RpcTransport { defHeader.resolve(parseMetadataFromResponseHeaders(fetchResponse.headers)); - switch (fetchResponse.type) { + // Cloudflare Workers throw when the type property of a fetch response + // is accessed, so wrap access with try/catch. See: + // * https://developers.cloudflare.com/workers/runtime-apis/response/#properties + // * https://github.com/cloudflare/miniflare/blob/72f046e/packages/core/src/standards/http.ts#L646 + let responseType + try { responseType = fetchResponse.type } catch {} + switch (responseType) { case "error": case "opaque": case "opaqueredirect":