Skip to main content

trillium_api/
json.rs

1use crate::{ApiConnExt, TryFromConn};
2use serde::{Serialize, de::DeserializeOwned};
3use std::ops::{Deref, DerefMut};
4use trillium::{Conn, Handler};
5
6/// A newtype wrapper struct for any [`serde::Serialize`] type. Note
7/// that this currently must own the serializable type.
8/// Body extractor
9#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Ord, PartialOrd, Hash)]
10pub struct Json<T>(pub T);
11
12impl<T> Json<T> {
13    /// construct a new Json
14    pub fn new(t: T) -> Self {
15        Self(t)
16    }
17
18    /// Unwrap this Json
19    pub fn into_inner(self) -> T {
20        self.0
21    }
22}
23
24impl<T> From<T> for Json<T> {
25    fn from(value: T) -> Self {
26        Self(value)
27    }
28}
29
30impl<T> Deref for Json<T> {
31    type Target = T;
32
33    fn deref(&self) -> &Self::Target {
34        &self.0
35    }
36}
37
38impl<T> DerefMut for Json<T> {
39    fn deref_mut(&mut self) -> &mut Self::Target {
40        &mut self.0
41    }
42}
43
44impl<Serializable> Handler for Json<Serializable>
45where
46    Serializable: Serialize + Send + Sync + 'static,
47{
48    async fn run(&self, conn: Conn) -> Conn {
49        conn.with_json(&self.0)
50    }
51}
52
53impl<T> TryFromConn for Json<T>
54where
55    T: DeserializeOwned + Send + Sync + 'static,
56{
57    type Error = crate::Error;
58
59    async fn try_from_conn(conn: &mut Conn) -> Result<Self, Self::Error> {
60        conn.deserialize_json().await.map(Self)
61    }
62}