server_fn/codec/
serde_lite.rs1use 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
9pub 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
53pub type SerdeLite = Post<SerdeLiteEncoding>;
55
56pub type PatchSerdeLite = Patch<SerdeLiteEncoding>;
60
61pub type PutSerdeLite = Put<SerdeLiteEncoding>;