Skip to main content

nestrs_core/
execution_context.rs

1use axum::http::request::Parts;
2
3/// Active host kind (NestJS [`ArgumentsHost#getType`](https://docs.nestjs.com/fundamentals/execution-context)).
4#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5pub enum HostType {
6    Http,
7    Rpc,
8    Ws,
9    Unknown,
10}
11
12/// Cross-cutting context similar to NestJS [`ExecutionContext`](https://docs.nestjs.com/fundamentals/execution-context)
13/// / `ArgumentsHost` for HTTP handlers (RPC/WS can set [`HostType`] when wired manually).
14#[derive(Clone, Debug)]
15pub struct ExecutionContext {
16    host_type: HostType,
17    pub method: axum::http::Method,
18    pub path_and_query: String,
19}
20
21impl ExecutionContext {
22    pub fn from_http_parts(parts: &Parts) -> Self {
23        let path_and_query = parts
24            .uri
25            .path_and_query()
26            .map(|pq| pq.as_str().to_owned())
27            .unwrap_or_else(|| parts.uri.path().to_owned());
28        Self {
29            host_type: HostType::Http,
30            method: parts.method.clone(),
31            path_and_query,
32        }
33    }
34
35    pub fn get_type(&self) -> HostType {
36        self.host_type
37    }
38
39    /// 32-hex W3C trace id from the ambient trace context, when one was
40    /// installed (see `nestrs::core::with_trace_context`).
41    pub fn trace_id(&self) -> Option<String> {
42        crate::current_trace_context().map(|t| t.trace_id_hex())
43    }
44
45    /// 16-hex W3C span id from the ambient trace context.
46    pub fn span_id(&self) -> Option<String> {
47        crate::current_trace_context().map(|t| t.span_id_hex())
48    }
49
50    /// 2-hex W3C trace flags from the ambient trace context.
51    pub fn trace_flags(&self) -> Option<String> {
52        crate::current_trace_context().map(|t| t.trace_flags_hex())
53    }
54
55    pub fn switch_to_http(&self) -> HttpExecutionArguments<'_> {
56        HttpExecutionArguments { ctx: self }
57    }
58}
59
60/// NestJS `switchToHttp().getRequest()`-style view without storing the full Axum request type.
61pub struct HttpExecutionArguments<'a> {
62    ctx: &'a ExecutionContext,
63}
64
65impl<'a> HttpExecutionArguments<'a> {
66    pub fn method(&self) -> &'a axum::http::Method {
67        &self.ctx.method
68    }
69
70    pub fn path_and_query(&self) -> &'a str {
71        self.ctx.path_and_query.as_str()
72    }
73}