server_fn/codec/
json.rs

1use super::{Patch, Post, Put};
2use crate::{ContentType, Decodes, Encodes, Format, FormatType};
3use bytes::Bytes;
4use serde::{de::DeserializeOwned, Serialize};
5
6/// Serializes and deserializes JSON with [`serde_json`].
7pub struct JsonEncoding;
8
9impl ContentType for JsonEncoding {
10    const CONTENT_TYPE: &'static str = "application/json";
11}
12
13impl FormatType for JsonEncoding {
14    const FORMAT_TYPE: Format = Format::Text;
15}
16
17impl<T> Encodes<T> for JsonEncoding
18where
19    T: Serialize,
20{
21    type Error = serde_json::Error;
22
23    fn encode(output: &T) -> Result<Bytes, Self::Error> {
24        serde_json::to_vec(output).map(Bytes::from)
25    }
26}
27
28impl<T> Decodes<T> for JsonEncoding
29where
30    T: DeserializeOwned,
31{
32    type Error = serde_json::Error;
33
34    fn decode(bytes: Bytes) -> Result<T, Self::Error> {
35        serde_json::from_slice(&bytes)
36    }
37}
38
39/// Pass arguments and receive responses as JSON in the body of a `POST` request.
40pub type Json = Post<JsonEncoding>;
41
42/// Pass arguments and receive responses as JSON in the body of a `PATCH` request.
43/// **Note**: Browser support for `PATCH` requests without JS/WASM may be poor.
44/// Consider using a `POST` request if functionality without JS/WASM is required.
45pub type PatchJson = Patch<JsonEncoding>;
46
47/// Pass arguments and receive responses as JSON in the body of a `PUT` request.
48/// **Note**: Browser support for `PUT` requests without JS/WASM may be poor.
49/// Consider using a `POST` request if functionality without JS/WASM is required.
50pub type PutJson = Put<JsonEncoding>;