Skip to content

Commit

Permalink
feat: Add web worker support
Browse files Browse the repository at this point in the history
  • Loading branch information
tjhorner committed Feb 29, 2024
1 parent 0350052 commit 6c41064
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
19 changes: 18 additions & 1 deletion javascript/net/grpc/web/grpcwebclientbase.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ const MethodDescriptor = goog.requireType('grpc.web.MethodDescriptor');
const Request = goog.require('grpc.web.Request');
const RpcError = goog.require('grpc.web.RpcError');
const StatusCode = goog.require('grpc.web.StatusCode');
const FetchXmlHttpFactory = goog.require('goog.net.FetchXmlHttpFactory');
const XhrIo = goog.require('goog.net.XhrIo');
const googCrypt = goog.require('goog.crypt.base64');
const {Status} = goog.require('grpc.web.Status');
Expand Down Expand Up @@ -92,6 +93,13 @@ class GrpcWebClientBase {
this.unaryInterceptors_ = options.unaryInterceptors ||
goog.getObjectByName('unaryInterceptors', options) || [];

/**
* @const {WorkerGlobalScope}
* @private {boolean}
*/
this.workerScope = options.workerScope ||
goog.getObjectByName('workerScope', options) || null;

/** @const @private {?XhrIo} */
this.xhrIo_ = xhrIo || null;
}
Expand Down Expand Up @@ -173,6 +181,15 @@ class GrpcWebClientBase {
this, methodDescriptor.createRequest(requestMessage, metadata)));
}

createXhrIo_() {
if (this.workerScope) {
return new XhrIo(new FetchXmlHttpFactory({
worker: this.workerScope
}));
}
return new XhrIo();
}

/**
* @private
* @template REQUEST, RESPONSE
Expand All @@ -184,7 +201,7 @@ class GrpcWebClientBase {
const methodDescriptor = request.getMethodDescriptor();
let path = hostname + methodDescriptor.getName();

const xhr = this.xhrIo_ ? this.xhrIo_ : new XhrIo();
const xhr = this.xhrIo_ ? this.xhrIo_ : this.createXhrIo_();
xhr.setWithCredentials(this.withCredentials_);

const genericTransportInterface = {
Expand Down
1 change: 1 addition & 0 deletions packages/grpc-web/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ declare module "grpc-web" {
withCredentials?: boolean;
unaryInterceptors?: UnaryInterceptor<unknown, unknown>[];
streamInterceptors?: StreamInterceptor<unknown, unknown>[];
workerScope?: WorkerGlobalScope;
}

export class GrpcWebClientBase extends AbstractClientBase {
Expand Down
2 changes: 1 addition & 1 deletion packages/grpc-web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
"devDependencies": {
"@types/google-protobuf": "~3.7.0",
"command-exists": "~1.2.8",
"google-closure-compiler": "~20200224.0.0",
"google-closure-compiler": "~20220301.0.0",
"google-closure-deps": "~20210601.0.0",
"google-closure-library": "~20210808.0.0",
"google-protobuf": "~3.14.0",
Expand Down

0 comments on commit 6c41064

Please sign in to comment.