DEV Community

sdcaulley
sdcaulley

Posted on

Using My npm Packages in a Node.js gRPC Server

Having created a local npm package for the protobuf files in my cluster, I can now install that package and use it in a gRPC server.

I install the package:

npm install --save <path to package>
Enter fullscreen mode Exit fullscreen mode

And use it like I would any other installed npm package:

const { exportName } = require('<package name>');
Enter fullscreen mode Exit fullscreen mode

For the gRPC server, I will use the Services export, since it the file that has the definitions for the operations that were defined.

So, my server ends up looking like this:

const grpc = require('@grpc/grpc-js');
const <service_name>Services = require('<package_name>');
const protoDescription = grpc.loadPackageDefinition(<service name>Services);

// operation declarations as logic

async function main() {
  const server = new grpc.Server();
  server.addService(protoDescription.<name_of_service>.service, {
    // operations
  });

  server.bindAsync(
    `0.0.0.0:${config.port}`,
    grpc.ServerCredentials.createInsecure(),
    err => {
      if(err) {
        console.error('err: ', err);
      }
      server.start();
      console.log('Server Started');
    }
  );
}

main();
Enter fullscreen mode Exit fullscreen mode

There is one major difference between using my generated file and directly using a proto file:

  • When directly using a proto file, you need to import the proto file, create a packageDefinition using @grpc/proto-loader, and feed that to grpc.loadPackageDefinition().

So the server file would look like this:

const grpc = require('@grpc/grpc-js');
const protoLoader = require('@grpc/proto-loader');
const PROTO_PATH = '<path_to_proto_file';
const packageDefinition = protoLoader.loadSync(PROTO_PATH);
const protoDescription = grpc.loadPackageDefinition(packageDefinition);

// operation declarations as logic

async function main() {
  const server = new grpc.Server();
  server.addService(protoDescription.<name_of_service>.service, {
    // operations
  });

  server.bindAsync(
    `0.0.0.0:${config.port}`,
    grpc.ServerCredentials.createInsecure(),
    err => {
      if(err) {
        console.error('err: ', err);
      }
      server.start();
      console.log('Server Started');
    }
  );
}

main();
Enter fullscreen mode Exit fullscreen mode

The generated files skip this step, because I used the --grpc_out:generate_package_definition flag for the grpc-tools.

Top comments (0)