📄
StackExchangeSearchProvider.cs
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
using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Json; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.Extensions.Options; using MSearch.Domain; namespace MSearch.SearchProviders.StackExchange; internal sealed class StackExchangeSearchProvider(IOptions<StackExchangeOptions> options, HttpClient httpClient) : ISearchProvider { private readonly string apiKey = options.Value.ApiKey; private readonly string site = options.Value.Site; public async IAsyncEnumerable<SearchResult> Search( SearchQuery query, [EnumeratorCancellation] CancellationToken cancellationToken ) { var response = await httpClient.GetFromJsonAsync( $"search/advanced?order=desc&sort=relevance&pagesize=10&site={site}&q={Uri.EscapeDataString(query.Term)}&key={apiKey}", StackExchangeJsonSerializerContext.Default.StackExchangeResponse, cancellationToken ); if (response is null) { yield break; } foreach (var item in response.Items) { yield return Map(item); } } private static SearchResult Map(StackExchangeItem item) => new(item.Title, Summary: null, new(item.Link)); }