grpc / grpc-dart

The Dart language implementation of gRPC.
https://pub.dev/packages/grpc
Apache License 2.0
861 stars 271 forks source link

How to check if metadata header has been set? #498

Closed Pante closed 3 years ago

Pante commented 3 years ago

Hey there, how do I check if a metadata header has been set? I currently have a ClientInterceptor that asynchronously attaches a authentication token to each request. At the moment, the request is simply sent without an authentication token if the application is not currently authenticated which isn't ideal since it's needlessly invoking the gRPC server. Ideally, the request would be cancelled by the client without having to make the round trip.

class AuthenticationInterceptor extends ClientInterceptor {

  @override
  ResponseFuture<R> interceptUnary<Q, R>(ClientMethod<Q, R> method, Q request, CallOptions options, ClientUnaryInvoker<Q, R> invoker) => super.interceptUnary(
      method,
      request,
      options.mergedWith(CallOptions(providers: [attach])),
      invoker
  );

    Future<void> attach(Map<String, String> metadata, String _) async {
      final token = await someOtherclass.getToken();
      if (token != null) {
        metadata['Authorization'] = 'Bearer $token';
      }
    }
  }
}
mraleph commented 3 years ago

You can throw an error from the MetadataProvider if you don't have a token that would terminate the call with error.