2

I am using grpc+protocol buffers in Flutter Mobile Client. My question is how can I add interceptors to grpc request/responses so that I will be able to log as much as I want from the same place? I also need to send these request/responses to another client for some purpose.

I would appreciate you help on this.

Khamidjon Khamidov
  • 6,783
  • 6
  • 31
  • 62

1 Answers1

1

Finally I found an answer!

First create interceptor class:

class InterceptorInvocation {
  final int id;
  final int unary;
  final int streaming;

  InterceptorInvocation(this.id, this.unary, this.streaming);

  @override
  String toString() {
    return '{id: ${id}, unary: ${unary}, streaming: ${streaming}}';
  }
}

class GRPCInterceptor implements ClientInterceptor {
  final int _id = 1;
  int _unary = 0;
  int _streaming = 0;

  static final _invocations = <InterceptorInvocation>[];

  @override
  ResponseFuture<R> interceptUnary<Q, R>(ClientMethod<Q, R> method, Q request,
      CallOptions options, ClientUnaryInvoker<Q, R> invoker) {
    _invocations.add(InterceptorInvocation(_id, ++_unary, _streaming));

    print('unary grpc message is here');
    return invoker(method, request, _inject(options));
  }

  @override
  ResponseStream<R> interceptStreaming<Q, R>(
      ClientMethod<Q, R> method,
      Stream<Q> requests,
      CallOptions options,
      ClientStreamingInvoker<Q, R> invoker) {
    _invocations.add(InterceptorInvocation(_id, _unary, ++_streaming));


    print('streaming grpc message is here');

    return invoker(method, requests, _inject(options));
  }

  CallOptions _inject(CallOptions options) {
    return options.mergedWith(CallOptions(metadata: {
      'x-interceptor': _invocations.map((i) => i.toString()).join(', '),
    }));
  }

  static void tearDown() {
    _invocations.clear();
  }
}

in your service client you need to call this like this;

_grpcClient = TaskMobileVideoServiceClient(
          clientChannel,
          interceptors: [GRPCInterceptor()],
        )
Khamidjon Khamidov
  • 6,783
  • 6
  • 31
  • 62