From 99c611223718a1e32290fe06845d3733edb30465 Mon Sep 17 00:00:00 2001 From: SonicGD Date: Tue, 26 Mar 2024 11:12:39 +0500 Subject: [PATCH] feat: add metadata provider --- .../GrpcClientModuleOptions.cs | 28 +++++++++++++++++++ .../IGrpcMetadataProvider.cs | 6 ++++ 2 files changed, 34 insertions(+) create mode 100644 src/Sitko.Core.Grpc.Client/IGrpcMetadataProvider.cs diff --git a/src/Sitko.Core.Grpc.Client/GrpcClientModuleOptions.cs b/src/Sitko.Core.Grpc.Client/GrpcClientModuleOptions.cs index a40b9589b..944dac179 100644 --- a/src/Sitko.Core.Grpc.Client/GrpcClientModuleOptions.cs +++ b/src/Sitko.Core.Grpc.Client/GrpcClientModuleOptions.cs @@ -29,6 +29,34 @@ internal void ConfigureClient(IServiceCollection services, IHttpClientBuilder bu configureAuthAction?.Invoke(services, builder); } + public GrpcClientModuleOptions AddMetadataProvider() + where TMetadataProvider : class, IGrpcMetadataProvider + { + configureAuthAction = (services, builder) => + { + services.TryAddTransient(); + builder.AddCallCredentials(async (_, metadata, serviceProvider) => + { + var provider = serviceProvider.GetRequiredService(); + var newMetadata = await provider.GetMetadataAsync(); + if (newMetadata?.Count > 0) + { + foreach (var (key, value) in newMetadata) + { + var oldEntries = metadata.GetAll(key); + foreach (var entry in oldEntries) + { + metadata.Remove(entry); + } + + metadata.Add(key, value); + } + } + }); + }; + return this; + } + public GrpcClientModuleOptions AddTokenAuth() where TTokenProvider : class, IGrpcTokenProvider { diff --git a/src/Sitko.Core.Grpc.Client/IGrpcMetadataProvider.cs b/src/Sitko.Core.Grpc.Client/IGrpcMetadataProvider.cs new file mode 100644 index 000000000..c68a314ea --- /dev/null +++ b/src/Sitko.Core.Grpc.Client/IGrpcMetadataProvider.cs @@ -0,0 +1,6 @@ +namespace Sitko.Core.Grpc.Client; + +public interface IGrpcMetadataProvider +{ + Task?> GetMetadataAsync(); +}