hypershell_json_components/providers/
handler.rs

1use alloc::vec::Vec;
2use core::marker::PhantomData;
3
4use cgp::extra::handler::{Handler, HandlerComponent};
5use cgp::prelude::*;
6use hypershell_components::dsl::DecodeJson;
7use serde::Serialize;
8use serde::de::DeserializeOwned;
9
10#[cgp_new_provider]
11impl<Context, Input, Output> Handler<Context, DecodeJson<Output>, Input> for HandleDecodeJson
12where
13    Context: CanRaiseAsyncError<serde_json::Error>,
14    Input: Send + AsRef<[u8]>,
15    Output: Send + DeserializeOwned,
16{
17    type Output = Output;
18
19    async fn handle(
20        _context: &Context,
21        _tag: PhantomData<DecodeJson<Output>>,
22        input: Input,
23    ) -> Result<Self::Output, Context::Error> {
24        let output = serde_json::from_slice(input.as_ref()).map_err(Context::raise_error)?;
25        Ok(output)
26    }
27}
28
29#[cgp_new_provider]
30impl<Context, Code, Input> Handler<Context, Code, Input> for HandleEncodeJson
31where
32    Context: CanRaiseAsyncError<serde_json::Error>,
33    Input: Send + Serialize,
34    Code: Send,
35{
36    type Output = Vec<u8>;
37
38    async fn handle(
39        _context: &Context,
40        _tag: PhantomData<Code>,
41        input: Input,
42    ) -> Result<Vec<u8>, Context::Error> {
43        let output = serde_json::to_vec(&input).map_err(Context::raise_error)?;
44        Ok(output)
45    }
46}