momento_functions/macros/
function_web.rs

1/// Create a handler that accepts a post payload and returns a response.
2///
3/// You can use raw bytes, or json-marshalled types.
4///
5/// **Raw:**
6/// ```rust
7/// momento_functions::post!(ping);
8/// fn ping(payload: Vec<u8>) -> FunctionResult<Vec<u8>> {
9///     Ok(b"pong".to_vec())
10/// }
11/// ```
12///
13/// **Typed JSON:**
14/// ```rust
15/// #[derive(serde::Deserialize)]
16/// struct Request {
17///     name: String,
18/// }
19/// #[derive(serde::Serialize)]
20/// struct Response {
21///     message: String,
22/// }
23///
24/// momento_functions::post!(greet, Request, Response);
25/// fn greet(request: Request) -> FunctionResult<Response> {
26///     Ok(Response { message: format!("Hello, {}!", request.name) })
27/// }
28/// ```
29#[macro_export]
30macro_rules! post {
31    ($post_handler: ident) => {
32        use momento_functions_host::FunctionResult;
33        struct WebFunction;
34        momento_functions_wit::__export_web_function_impl!(WebFunction);
35
36        #[automatically_derived]
37        impl momento_functions_wit::function_web::exports::momento::functions::guest_function_web::Guest for WebFunction {
38            fn post(payload: Vec<u8>) -> Result<Vec<u8>, momento_functions_wit::function_web::momento::functions::types::InvocationError> {
39                $post_handler(payload).map_err(Into::into)
40            }
41        }
42    };
43
44    ($post_handler: ident, $request: ident, $response: ident) => {
45        use momento_functions_host::FunctionResult;
46        struct WebFunction;
47        momento_functions_wit::function_web::export_web_function!(WebFunction);
48
49        #[automatically_derived]
50        impl momento_functions_wit::function_web::exports::momento::functions::guest_function_web::Guest for WebFunction {
51            fn post(payload: Vec<u8>) -> Result<Vec<u8>, momento_functions_wit::function_web::momento::functions::types::InvocationError> {
52                let payload: $request = serde_json::from_slice(&payload)
53                    .map_err(|e| momento_functions_wit::function_web::momento::functions::types::InvocationError::RequestError(format!("could not deserialize json: {e:?}")))?;
54                let response: $response = $post_handler(payload)?;
55                serde_json::to_vec(&response)
56                    .map_err(|e| momento_functions_wit::function_web::momento::functions::types::InvocationError::RequestError(format!("could not serialize json: {e:?}")))
57            }
58        }
59    }
60}