Search code examples
javascriptgrpc-node

Issue when migrating to @grpc/grpc-js from grpc


Im trying to migrate an older Node app that is using grpc to @grpc/grpc-js. But facing issue when trying to get

In the (old) grpc package the messages definitions are returning functions and there are some methods exposed - decode, decode64, encode etc.

old-grpc

And the new @grpc/grpc-js is returning the structure.

grpc-js

Code

With @grpc/grpc-js and @grpc/proto-loader:

const grpc = require("@grpc/grpc-js");
const protoLoader = require("@grpc/proto-loader");

const packageDefinition = protoLoader.loadSync(
  "path.to.proto",
  { keepCase: true, longs: String, enums: String, defaults: true, oneofs: true }
);

const { MyService } = grpc.loadPackageDefinition(packageDefinition);

With grpc:

const grpc = require('grpc');

const { MyService } = grpc.load("path.to.proto");

Part of .proto

syntax="proto3";

package MyService;

message FunctionRequestHeader {
    int32 functionId = 1;
    string version = 2; 
}

Couple of questions:

  • is there a way to use the old methods? like:
const functionHeader = MyService.FunctionRequestHeader.decode(
    request.metadata.get("functionrequestheader-bin")[0]
);
  • since the new package is returning just objects i no longer can create new instance of a message (or at least i cant find it). In the old code i used to be able to write something like this:
const a = new MyService.FunctionRequestHeader({
  functionId: 123,
  version: "something goes here"
});

But now im getting that FunctionRequestHeader is not a function


Solution

  • The protobuf message classes were deliberately not exposed in the APIs of @grpc/grpc-js and @grpc/proto-loader because they represent a large API surface that those libraries do not directly control, and they are not necessary for the regular operation of gRPC APIs.

    If you still want to interact with protobuf messages directly, you will need to directly use a protobuf implementation yourself. @grpc/proto-loader uses protobufjs, but there are others available too.