-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPdfClientFactory.cs
More file actions
78 lines (64 loc) · 2.63 KB
/
Copy pathPdfClientFactory.cs
File metadata and controls
78 lines (64 loc) · 2.63 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
74
75
76
77
78
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using PDFinch.Client.Common;
namespace PDFinch.Client
{
/// <summary>
/// A naive implementation of a client factory.
/// TODO: check (I)HttpClient(Factory) usage.
/// </summary>
public class PdfClientFactory : IPdfClientFactory
{
private readonly List<PdfClientOptions> _optionsCache = new();
private PdfClientOptionsList? _optionsList;
private readonly ConcurrentDictionary<string, PdfClient> _clientCache = new();
/// <summary>
/// Registers a PDF client (<see cref="IPdfClient"/>) accoring to the provided <paramref name="options"></paramref>.
/// </summary>
/// <param name="options"></param>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentException"></exception>
public void RegisterPdfClient(PdfClientOptions options)
{
if (string.IsNullOrEmpty(options.ApiKey))
{
throw new ArgumentNullException(nameof(options.ApiKey));
}
if (string.IsNullOrEmpty(options.ApiSecret))
{
throw new ArgumentNullException(nameof(options.ApiSecret));
}
_optionsCache.Add(options);
}
/// <inheritdoc />
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentException"></exception>
public IPdfClient GetPdfClient(string? nameOrApiKey = null)
{
if (_optionsCache?.Any() != true)
{
throw new InvalidOperationException("There are no clients registered. Call RegisterPdfClient() before calling GetPdfClient().");
}
_optionsList ??= new PdfClientOptionsList(_optionsCache);
var options = _optionsList.GetClientOptions(nameOrApiKey);
if (!_clientCache.TryGetValue(options.ApiKey, out var client) || client.IsExpired())
{
// TODO: this leaves an HttpClient to get garbage collected, eventually. How does this hold up under load?
client = _clientCache[options.ApiKey] = new PdfClient(CreateHttpClient(options.GetBaseUrl()), options);
}
return client;
}
private static HttpClient CreateHttpClient(Uri baseUri)
{
var httpClient = new HttpClient
{
BaseAddress = baseUri,
};
httpClient.SetUserAgentToAssemblyVersion();
return httpClient;
}
}
}