Skip to main content

trillium_api/
json.rs

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