Skip to main content

server_fn/codec/
serde_lite.rs

1use crate::{
2    codec::{Patch, Post, Put},
3    error::ServerFnErrorErr,
4    ContentType, Decodes, Encodes, Format, FormatType,
5};
6use bytes::Bytes;
7use serde_lite::{Deserialize, Serialize};
8
9/// Pass arguments and receive responses as JSON in the body of a `POST` request.
10pub struct SerdeLiteEncoding;
11
12impl ContentType for SerdeLiteEncoding {
13    const CONTENT_TYPE: &'static str = "application/json";
14}
15
16impl FormatType for SerdeLiteEncoding {
17    const FORMAT_TYPE: Format = Format::Text;
18}
19
20impl<T> Encodes<T> for SerdeLiteEncoding
21where
22    T: Serialize,
23{
24    type Error = ServerFnErrorErr;
25
26    fn encode(value: &T) -> Result<Bytes, Self::Error> {
27        serde_json::to_vec(
28            &value
29                .serialize()
30                .map_err(|e| ServerFnErrorErr::Serialization(e.to_string()))?,
31        )
32        .map_err(|e| ServerFnErrorErr::Serialization(e.to_string()))
33        .map(Bytes::from)
34    }
35}
36
37impl<T> Decodes<T> for SerdeLiteEncoding
38where
39    T: Deserialize,
40{
41    type Error = ServerFnErrorErr;
42
43    fn decode(bytes: Bytes) -> Result<T, Self::Error> {
44        T::deserialize(
45            &serde_json::from_slice(&bytes).map_err(|e| {
46                ServerFnErrorErr::Deserialization(e.to_string())
47            })?,
48        )
49        .map_err(|e| ServerFnErrorErr::Deserialization(e.to_string()))
50    }
51}
52
53/// Pass arguments and receive responses as JSON in the body of a `POST` request.
54pub type SerdeLite = Post<SerdeLiteEncoding>;
55
56/// Pass arguments and receive responses as JSON in the body of a `PATCH` request.
57/// **Note**: Browser support for `PATCH` requests without JS/WASM may be poor.
58/// Consider using a `POST` request if functionality without JS/WASM is required.
59pub type PatchSerdeLite = Patch<SerdeLiteEncoding>;
60
61/// Pass arguments and receive responses as JSON in the body of a `PUT` request.
62/// **Note**: Browser support for `PUT` requests without JS/WASM may be poor.
63/// Consider using a `POST` request if functionality without JS/WASM is required.
64pub type PutSerdeLite = Put<SerdeLiteEncoding>;