using Microsoft.AspNetCore.Http;
namespace DorkNet.Server.Compat;
/// Helpers to read the active
/// off the current request. The version is set by
/// VersionDetectionMiddleware early in the pipeline so any
/// downstream consumer (controllers, services, filters) can resolve
/// it without re-parsing the header.
public static class HttpContextExtensions
{
private const string ClientVersionKey = "DorkNet.ClientVersion";
/// Stamp the resolved version on the request. Called by
/// VersionDetectionMiddleware; not for general use.
internal static void SetClientVersion(this HttpContext ctx, ClientVersion v)
=> ctx.Items[ClientVersionKey] = v;
/// The client version for this request. Returns
/// if the middleware hasn't
/// run (e.g. a unit test that calls a controller method directly)
/// rather than null, so callers can safely branch on
/// Generation without null-checks.
public static ClientVersion ClientVersion(this HttpContext ctx)
=> ctx.Items.TryGetValue(ClientVersionKey, out var v)
&& v is ClientVersion cv
? cv
: Compat.ClientVersion.Unknown;
}