Skip to content

Commit

Permalink
Guard access of response.type to support Cloudflare Workers
Browse files Browse the repository at this point in the history
This is #321, but applied to the grpcweb-transport as well.

All tests pass locally.
  • Loading branch information
timostamm committed Jun 3, 2022
1 parent 80de3ee commit 2724079
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
6 changes: 5 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
### unreleased changes

none

Bug fixes:

- Guard access of response.type to support Cloudflare Workers, see #321
Thanks to @mikeylemmon for the fix!


### v2.6.0
Expand Down
10 changes: 9 additions & 1 deletion packages/grpcweb-transport/src/grpc-web-format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,13 +86,21 @@ export function readGrpcWebResponseHeader(headers: HttpHeaders, httpStatus: numb
export function readGrpcWebResponseHeader(headersOrFetchResponse: HttpHeaders | Response, httpStatus?: number, httpStatusText?: string): [GrpcStatusCode, string | undefined, RpcMetadata] {
if (arguments.length === 1) {
let fetchResponse = headersOrFetchResponse as Response;
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":
// see https://developer.mozilla.org/en-US/docs/Web/API/Response/type
throw new RpcError(`fetch response type ${fetchResponse.type}`, GrpcStatusCode[GrpcStatusCode.UNKNOWN]);
}

return readGrpcWebResponseHeader(
fetchHeadersToHttp(fetchResponse.headers),
fetchResponse.status,
Expand Down
8 changes: 7 additions & 1 deletion packages/twirp-transport/src/twirp-transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand Down

0 comments on commit 2724079

Please sign in to comment.