-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEndpoint.cs
More file actions
74 lines (61 loc) · 2.37 KB
/
Copy pathEndpoint.cs
File metadata and controls
74 lines (61 loc) · 2.37 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
namespace Shiny.Net.HttpServer.Routing;
/// <summary>
/// A handler the router can select, plus whatever metadata was attached when it was registered.
/// Shaped after ASP.NET Core's <c>Endpoint</c> so the mental model carries over.
/// </summary>
public class Endpoint
{
readonly List<object> metadata;
public Endpoint(RequestDelegate requestDelegate, string displayName, params object[]? metadata)
{
ArgumentNullException.ThrowIfNull(requestDelegate);
this.RequestDelegate = requestDelegate;
this.DisplayName = displayName;
this.metadata = metadata is { Length: > 0 } ? [.. metadata] : [];
}
public RequestDelegate RequestDelegate { get; }
/// <summary>Human-readable name used in logs and diagnostics, e.g. <c>GET /users/{id}</c>.</summary>
public string DisplayName { get; }
public IReadOnlyList<object> Metadata => this.metadata;
/// <summary>
/// Attaches metadata after registration. This is what lets a raw route be described for
/// OpenAPI without every <c>Map</c> overload growing a parameter for it.
/// </summary>
public Endpoint WithMetadata(object item)
{
ArgumentNullException.ThrowIfNull(item);
this.metadata.Add(item);
return this;
}
/// <summary>
/// Returns the last metadata item assignable to <typeparamref name="T"/>, or null. Last wins so
/// that metadata added closer to the endpoint overrides a convention applied to the whole group.
/// </summary>
public T? GetMetadata<T>() where T : class
{
for (var i = this.metadata.Count - 1; i >= 0; i--)
{
if (this.metadata[i] is T match)
return match;
}
return null;
}
public override string ToString() => this.DisplayName;
}
/// <summary>An <see cref="Endpoint"/> selected by matching a route template and an HTTP method.</summary>
public sealed class RouteEndpoint : Endpoint
{
public RouteEndpoint(
RequestDelegate requestDelegate,
string method,
RouteTemplate template,
params object[]? metadata
) : base(requestDelegate, $"{method} {template.RawText}", metadata)
{
this.Method = method;
this.Template = template;
}
/// <summary>The HTTP method this endpoint answers, uppercased.</summary>
public string Method { get; }
public RouteTemplate Template { get; }
}