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
use std::{
    fmt,
    ops::{Deref, DerefMut},
};

use serde::de::DeserializeOwned;

use viz_utils::{futures::future::BoxFuture, serde::urlencoded, tracing};

use crate::{types::PayloadError, Context, Extract, Result};

/// Extract typed information from the request's query
#[derive(Clone)]
pub struct Query<T>(pub T);

impl<T> Query<T> {
    /// Deconstruct to an inner value
    pub fn into_inner(self) -> T {
        self.0
    }
}

impl<T> AsRef<T> for Query<T> {
    fn as_ref(&self) -> &T {
        &self.0
    }
}

impl<T> Deref for Query<T> {
    type Target = T;

    fn deref(&self) -> &T {
        &self.0
    }
}

impl<T> DerefMut for Query<T> {
    fn deref_mut(&mut self) -> &mut T {
        &mut self.0
    }
}

impl<T: fmt::Debug> fmt::Debug for Query<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        T::fmt(self, f)
    }
}

impl<T> Extract for Query<T>
where
    T: DeserializeOwned,
{
    type Error = PayloadError;

    #[inline]
    fn extract(cx: &mut Context) -> BoxFuture<'_, Result<Self, Self::Error>> {
        Box::pin(async move { cx.query().map(Self) })
    }
}

impl Context {
    /// Gets query parameters from the path
    pub fn query<T>(&self) -> Result<T, PayloadError>
    where
        T: DeserializeOwned,
    {
        urlencoded::from_str(self.query_str()).map_err(|e| {
            tracing::error!("Query deserialize error: {}", e);
            PayloadError::Parse
        })
    }
}