intrepid_core/extract/
extractor.rs

1use std::convert::Infallible;
2
3use crate::{Context, Frame};
4
5use super::ExtractorError;
6
7/// Implement extract to allow for extracting values from an action.
8pub trait Extractor<State> {
9    /// The error type for this extractor. Anything that can be converted into an extractor error
10    /// can be used as an error type.
11    ///
12    /// Types that can be converted into an extractor error are:
13    ///
14    /// - `String`
15    /// - `Infallible`
16    /// - `tower::BoxError`
17    ///
18    type Error: Into<ExtractorError>;
19
20    /// Take an frame and a state and return a result containing the extracted value or the frame.
21    fn extract(frame: Frame, context: &Context<State>) -> Result<Self, Self::Error>
22    where
23        Self: Sized;
24
25    /// Extract a value from a frame and state, returning a result containing the extracted value
26    /// or an error coerced into a `crate::Error`.
27    fn extract_from_frame_and_state(frame: Frame, context: &Context<State>) -> crate::Result<Self>
28    where
29        Self: Sized,
30        Self::Error: Into<ExtractorError>,
31    {
32        match Self::extract(frame, context) {
33            Ok(value) => Ok(value),
34            Err(error) => Err(error.into().into()),
35        }
36    }
37}
38
39impl<State> Extractor<State> for Frame {
40    type Error = Infallible;
41
42    fn extract(
43        frame: Frame,
44        _: &Context<State>,
45    ) -> Result<Self, <crate::Frame as Extractor<State>>::Error> {
46        Ok(frame)
47    }
48}
49
50impl<State> Extractor<State> for String {
51    type Error = ExtractorError;
52
53    fn extract(frame: Frame, _: &Context<State>) -> Result<Self, Self::Error> {
54        Ok(frame.into())
55    }
56}