gRPC NodeJS Server Interceptors
This package provides an interface for gRPC Servers from @grpc/grpc-js
to be created with interceptors. Allows for intercepting incoming requests from gRPC clients as well as intercepting outgoing responses from the server.
Installation
npm:
npm install grpc-node-server-interceptors
yarn:
yarn add grpc-node-server-interceptors
Examples
This example shows how to intercept incoming gRPC client requests on your gRPC server:
import { status as GrpcStatus } from '@grpc/grpc-js`;
import GrpcServerWithInterceptors, { ServerInterceptor, ServerInterceptingCall } from 'grpc-node-server-interceptors';
const interceptors: ServerInterceptor<RequestType, RequestResponse>[] = [
(call, nextCall) => {
return new ServerInterceptingCall(nextCall(call), {
// This is called on every incoming client request before sent to the original handler
onReceiveMessage: (message, next) => {
// Continue unto the next interceptor
next(message);
},
// This is called on every outgoing server response before it is sent to the client
onSendMessage: (response, next) => {
if (response.status !== GrpcStatus.OK) {
log.error(response.status);
}
next(response);
},
});
}
]
const server = new GrpcServerWithInterceptors({
...channelOptions,
// List of global interceptors. These will be applied to all services added to the server through `addService`.
interceptors,
});
// Consume the new server the same way you would with `grpc.Server`
server.addService(serviceDefinition, handlers);
server.bindAsync(...);