namespace StellaOps.Microservice;
///
/// Default implementation of endpoint registry using path matchers.
///
public sealed class EndpointRegistry : IEndpointRegistry
{
private readonly List _endpoints = [];
private readonly bool _caseInsensitive;
///
/// Initializes a new instance of the class.
///
/// Whether path matching should be case-insensitive.
public EndpointRegistry(bool caseInsensitive = true)
{
_caseInsensitive = caseInsensitive;
}
///
/// Registers an endpoint descriptor.
///
/// The endpoint descriptor to register.
public void Register(EndpointDescriptor endpoint)
{
var matcher = new PathMatcher(endpoint.Path, _caseInsensitive);
_endpoints.Add(new RegisteredEndpoint(endpoint, matcher));
}
///
/// Registers multiple endpoint descriptors.
///
/// The endpoint descriptors to register.
public void RegisterAll(IEnumerable endpoints)
{
foreach (var endpoint in endpoints)
{
Register(endpoint);
}
}
///
public bool TryMatch(string method, string path, out EndpointMatch? match)
{
match = null;
foreach (var registered in _endpoints)
{
// Check method match (case-insensitive)
if (!string.Equals(registered.Endpoint.Method, method, StringComparison.OrdinalIgnoreCase))
continue;
// Check path match
if (registered.Matcher.TryMatch(path, out var parameters))
{
match = new EndpointMatch
{
Endpoint = registered.Endpoint,
PathParameters = parameters
};
return true;
}
}
return false;
}
///
public IReadOnlyList GetAllEndpoints()
{
return _endpoints.Select(e => e.Endpoint).ToList();
}
private sealed record RegisteredEndpoint(EndpointDescriptor Endpoint, PathMatcher Matcher);
}