Search code examples
javascriptnode.jsgrpcgrpc-node

How to add multiple services in grpc-js server?


Lets say I have .proto file like below:

service SvcOne{
    rpc MehtodOne(RequestOne) returns (ResponseOne) {}
}

service SvcTwo{
    rpc MethodTwo(RequestTwo) returns (ResponseTwo) {}
}

message RequestOne {
    string field_req= 1;
}

message ResponseOne {
    string field_res = 1;
}

message RequestTwo {
    string field_req= 1;
}

message ResponseTwo {
    string field_res = 1;
}

and then I try the code like below :

const server = new grpc.Server();      
server.addService(protoSchema.SvcOne.service, {MehtodOne: MethodOne});
server.addService(protoSchema.SvcTwo.service, {MethodTwo: MethodTwo});
server.bindAsync(
    "0.0.0.0:50051",
    grpc.ServerCredentials.createInsecure(),
    (err) => {
      if (err) {
        console.log("Error!");
      } else {
        routeServer.start();
        console.log("Server ready...");
      }
    }
  );

but got an error like this :

TypeError: Cannot read property 'service' of undefined

So I think I missing something in between.

The question: How to bind multiple services (SvcOne & SvcTwo) in grpc-js server ? or is that not possible in grpc-js ?


Solution

  • What I'm doing for this kind of scenario is define different services on it's own block in one proto file.

    package servicePackage;
    
    service Service1 {
        rpc Get(Empty) returns (Empty);
        rpc Insert(Empty) returns (Empty);
        rpc Remove(Empty) returns (Empty);
        rpc Update(Empty) returns (Empty);
    }
    
    service Service2 {
        rpc Get(Empty) returns (Empty);
        rpc Insert(Empty) returns (Empty);
        rpc Remove(Empty) returns (Empty);
        rpc Update(Empty) returns (Empty);
    }
    

    Then on addService just use each service name

    server.addService(grpcPackage.Service1.service, {
       Insert: async (call, callback) => {
           callback(null, null);
       },
    });
    
    server.addService(grpcPackage.Service2.service, {
       Insert: async (call, callback) => {
           callback(null, null);
       },
    });
    

    The rest like binding, protoLoading, server.start() stays the same.