Skip to main content

CallJson

Trait CallJson 

Source
pub trait CallJson {
    // Required methods
    fn receive_json<'life0, 'async_trait, T>(
        &'life0 mut self,
    ) -> Pin<Box<dyn Future<Output = Result<T>> + Send + 'async_trait>>
       where T: 'async_trait + DeserializeOwned,
             Self: 'async_trait,
             'life0: 'async_trait;
    fn respond_json<T: Serialize + Sync>(&self, value: &T) -> Response;
}
Expand description

Call-style JSON helpers — v1 design §5.1.

The extractor Json<T> covers the typed-handler style. This trait covers the call-style one, so both halves of Churust’s hybrid API can speak JSON:

use churust_core::{Call, Churust, TestClient};
use churust_json::CallJson;
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize)]
struct Note { text: String }

let app = Churust::server()
    .routing(|r| {
        r.post("/echo", |mut call: Call| async move {
            let note: Note = call.receive_json().await?;
            Ok::<_, churust_core::Error>(call.respond_json(&note))
        });
    })
    .build();

let res = TestClient::new(app)
    .post("/echo")
    .header("content-type", "application/json")
    .body(r#"{"text":"hi"}"#)
    .send()
    .await;
assert_eq!(res.text(), r#"{"text":"hi"}"#);

Lives here rather than in churust-core so the core keeps no serde_json dependency; bring it into scope with use churust_json::CallJson.

Required Methods§

Source

fn receive_json<'life0, 'async_trait, T>( &'life0 mut self, ) -> Pin<Box<dyn Future<Output = Result<T>> + Send + 'async_trait>>
where T: 'async_trait + DeserializeOwned, Self: 'async_trait, 'life0: 'async_trait,

Deserialize the request body as JSON.

Consumes the body. Fails with 400 Bad Request if it does not parse into T.

Source

fn respond_json<T: Serialize + Sync>(&self, value: &T) -> Response

Build a 200 OK JSON response from value.

Serialization failure yields a 500 rather than panicking: a type that cannot serialize is a bug in the application, not in the request.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementations on Foreign Types§

Source§

impl CallJson for Call

Source§

fn receive_json<'life0, 'async_trait, T>( &'life0 mut self, ) -> Pin<Box<dyn Future<Output = Result<T>> + Send + 'async_trait>>
where T: 'async_trait + DeserializeOwned, Self: 'async_trait, 'life0: 'async_trait,

Source§

fn respond_json<T: Serialize + Sync>(&self, value: &T) -> Response

Implementors§