request_body_json

Attribute Macro request_body_json 

Source
#[request_body_json]
Expand description

Parses the request body as JSON into a specified variable and type.

This attribute macro extracts and deserializes the request body content as JSON into a variable with the specified type. The body content is parsed as JSON using serde.

§Usage

use hyperlane::*;
use hyperlane_macros::*;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize, Clone)]
struct TestData {
    name: String,
    age: u32,
}

#[route("/request_body_json")]
struct RequestBodyJson;

impl ServerHook for RequestBodyJson {
    async fn new(_ctx: &Context) -> Self {
        Self
    }

    #[response_body(&format!("request data: {request_data_result:?}"))]
    #[request_body_json(request_data_result: TestData)]
    async fn handle(self, ctx: &Context) {}
}

impl RequestBodyJson {
    #[request_body_json(request_data_result: TestData)]
    async fn request_body_json_with_ref_self(&self, ctx: &Context) {}
}

#[request_body_json(request_data_result: TestData)]
async fn standalone_request_body_json_handler(ctx: &Context) {}

§Multi-Parameter Usage

use hyperlane::*;
use hyperlane_macros::*;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize, Clone)]
struct User {
    name: String,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
struct Config {
    debug: bool,
}

#[route("/multi_json")]
struct MultiJson;

impl ServerHook for MultiJson {
    async fn new(_ctx: &Context) -> Self {
        Self
    }

    #[response_body(&format!("user: {user:?}, config: {config:?}"))]
    #[request_body_json(user: User, config: Config)]
    async fn handle(self, ctx: &Context) {}
}

The macro accepts one or more variable_name: Type pairs separated by commas. Each variable will be available in the function scope as a Result<Type, JsonError>.