|
| 1 | +global using QueryEnumerable = System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, Microsoft.Extensions.Primitives.StringValues>>; |
| 2 | +using Microsoft.EntityFrameworkCore; |
| 3 | + |
| 4 | +namespace Nist; |
| 5 | + |
| 6 | +public static class WebhookEndpoints { |
| 7 | + public static IEndpointRouteBuilder MapGetWebhooks<TDb>(this IEndpointRouteBuilder app) where TDb : IDbWithWebhookRecord { |
| 8 | + app.MapGet($"/{WebhookUris.Webhooks}", GetWebhooks<TDb>); |
| 9 | + |
| 10 | + return app; |
| 11 | + } |
| 12 | + |
| 13 | + public static async Task<WebhookCollection> GetWebhooks<TDb>(HttpRequest request, TDb db) where TDb : IDbWithWebhookRecord { |
| 14 | + var query = WebhookQuery.Parse(request.Query); |
| 15 | + |
| 16 | + var counters = await db.WebhookRecords |
| 17 | + .GroupBy(r => r.Status) |
| 18 | + .Select(g => new { |
| 19 | + Status = g.Key, |
| 20 | + Count = g.Count() |
| 21 | + }) |
| 22 | + .ToArrayAsync(); |
| 23 | + |
| 24 | + var selected = await db.WebhookRecords |
| 25 | + .OrderByDescending(r => r.Id) |
| 26 | + .Take(query.Limit ?? WebhookQuery.DefaultLimit) |
| 27 | + .ToArrayAsync(); |
| 28 | + |
| 29 | + return new WebhookCollection( |
| 30 | + TotalCounts: counters.ToDictionary(c => c.Status.ToLower(), c => c.Count), |
| 31 | + Count: selected.Length, |
| 32 | + Items: selected |
| 33 | + ); |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +public class WebhookUris { |
| 38 | + public const string Webhooks = "webhooks"; |
| 39 | +} |
| 40 | + |
| 41 | +public record WebhookQuery( |
| 42 | + int? Limit = null |
| 43 | +) |
| 44 | +{ |
| 45 | + public const int DefaultLimit = 100; |
| 46 | + |
| 47 | + public static WebhookQuery Parse(IQueryCollection source) => new( |
| 48 | + Limit: source.SearchInt(nameof(Limit)) |
| 49 | + ); |
| 50 | +} |
| 51 | + |
| 52 | +public record WebhookCollection( |
| 53 | + Dictionary<string, int> TotalCounts, |
| 54 | + int Count, |
| 55 | + WebhookRecord[] Items |
| 56 | +); |
| 57 | + |
| 58 | +public static class QueryCollectionExtensions |
| 59 | +{ |
| 60 | + public static int? SearchInt(this QueryEnumerable query, string key) |
| 61 | + { |
| 62 | + var value = query.Search(key); |
| 63 | + return value == null ? null : int.Parse(value!); |
| 64 | + } |
| 65 | + |
| 66 | + public static string? Search(this QueryEnumerable query, string key) |
| 67 | + { |
| 68 | + var pair = query.FirstOrDefault(q => string.Equals(q.Key, key, StringComparison.InvariantCultureIgnoreCase)); |
| 69 | + return pair.Value.Where(x => x != null).FirstOrDefault(); |
| 70 | + } |
| 71 | +} |
| 72 | + |
0 commit comments