-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathGraphQlConfigurationExtensions.cs
More file actions
73 lines (60 loc) · 2.75 KB
/
Copy pathGraphQlConfigurationExtensions.cs
File metadata and controls
73 lines (60 loc) · 2.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using GraphQL.Client.Abstractions;
using GraphQL.Client.Http;
using Microsoft.Extensions.DependencyInjection;
using Sitecore.AspNetCore.SDK.GraphQL.Client.Models;
using Sitecore.AspNetCore.SDK.GraphQL.Exceptions;
using Sitecore.AspNetCore.SDK.GraphQL.Properties;
namespace Sitecore.AspNetCore.SDK.GraphQL.Extensions;
/// <summary>
/// Sitemap configuration.
/// </summary>
public static class GraphQLConfigurationExtensions
{
/// <summary>
/// Configuration for GraphQLClient.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
/// <param name="configuration">The <see cref="SitecoreGraphQLClientOptions" /> configuration for GraphQL client.</param>
/// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns>
public static IServiceCollection AddGraphQLClient(this IServiceCollection services, Action<SitecoreGraphQLClientOptions> configuration)
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(configuration);
services.Configure(configuration);
SitecoreGraphQLClientOptions options = TryGetConfiguration(configuration);
services.AddSingleton<IGraphQLClient, GraphQLHttpClient>(_ =>
{
if (!string.IsNullOrWhiteSpace(options.ContextId))
{
options.EndPoint = options.EndPoint.AddQueryString(
SitecoreGraphQLClientOptions.ContextIdQueryStringKey,
options.ContextId);
}
GraphQLHttpClient graphQlHttpClient = new(options.EndPoint!, options.GraphQLJsonSerializer);
if (!string.IsNullOrWhiteSpace(options.ApiKey))
{
graphQlHttpClient.HttpClient.DefaultRequestHeaders.Add(SitecoreGraphQLClientOptions.ApiKeyHeaderName, options.ApiKey);
}
return graphQlHttpClient;
});
return services;
}
private static SitecoreGraphQLClientOptions TryGetConfiguration(Action<SitecoreGraphQLClientOptions> configuration)
{
SitecoreGraphQLClientOptions options = new();
configuration.Invoke(options);
if (string.IsNullOrWhiteSpace(options.ApiKey) && string.IsNullOrWhiteSpace(options.ContextId))
{
throw new InvalidGraphQLConfigurationException(Resources.Exception_MissingApiKeyAndContextId);
}
if (options.EndPoint == null && !string.IsNullOrWhiteSpace(options.ContextId))
{
options.EndPoint = SitecoreGraphQLClientOptions.DefaultEdgeEndpoint;
}
else if (options.EndPoint == null)
{
throw new InvalidGraphQLConfigurationException(Resources.Exception_MissingEndpoint);
}
return options;
}
}