node.jsgrpc

Capture request/response in gRPC | How to use gRPC server interceptors in node.js?


I'm new to gRPC, I'm looking for a way to capture requests in gRPC before server functions are called. This might also be needed for responses. In another word, I'm trying to manipulate requests/responses before they're reach the controller.

I found a feature called interceptor, but as far as I understood this feature comes only with gRPC-web!

So how can I do this? Are Interceptors only for client-side?

For example, I wanna log every request in gRPC with some ability(maybe interceptors) how can I do this?

server.js

const grpc = require('@grpc/grpc-js');
const PROTO_PATH = './news.proto';
const protoLoader = require('@grpc/proto-loader');

const options = {
  keepCase: true,
  longs: String,
  enums: String,
  defaults: true,
  oneofs: true,
};
var packageDefinition = protoLoader.loadSync(PROTO_PATH, options);
const newsProto = grpc.loadPackageDefinition(packageDefinition);

const server = new grpc.Server();
let news = [
  { id: '1', title: 'Note 1', body: 'Content 1', postImage: 'Post image 1' },
  { id: '2', title: 'Note 2', body: 'Content 2', postImage: 'Post image 2' },
];


server.addService(newsProto.NewsService.service, {
  getAllNews: (call, callback) => {
    return callback(null, { news });
  }
});

server.bindAsync(
  '127.0.0.1:50051',
  grpc.ServerCredentials.createInsecure(),
  (error, port) => {
    if (error) {
      throw new Error(error);
    }

    console.log('Server at port:', port);
    console.log('Server running at http://127.0.0.1:50051');
    server.start();
  }
);

client.js

const grpc = require('@grpc/grpc-js');
const protoLoader = require('@grpc/proto-loader');
const PROTO_PATH = './news.proto';

const options = {
  keepCase: true,
  longs: String,
  enums: String,
  defaults: true,
  oneofs: true,
};

var packageDefinition = protoLoader.loadSync(PROTO_PATH, options);

const NewsService = grpc.loadPackageDefinition(packageDefinition).NewsService;

const client = new NewsService(
  'localhost:50051',
  grpc.credentials.createInsecure()
);

client.getAllNews({}, (error, news) => {
  if (error) throw error
  console.log(news);
});


Solution

  • A description of how to use server interceptors can be found in this document. In short, you create one or more interceptor functions that take a ServerInterceptingCall and produce another ServerInterceptingCall. Then you pass those functions in an array in the interceptors field of the options parameter to the Server constructor.