Skip to main content

respond

Function respond 

Source
pub async fn respond<Q, M, S>(
    schema: &Schema<Q, M, S>,
    body: &[u8],
    data: impl Any + Send + Sync,
) -> Response
where Q: ObjectType + 'static, M: ObjectType + 'static, S: SubscriptionType + 'static,
Expand description

Executes a POST /graphql JSON body against schema and returns the JSON response.

data is available to resolvers through ctx.data::<T>() (routes passes the Ctx). A body that is not a GraphQL request ({"query": ..., "variables": ...}) gets a 400 with {"errors": [{"message": "invalid GraphQL request: ..."}]}. Otherwise the status is 200 and resolver errors are in the body’s errors, as GraphQL expects.

§Examples

use async_graphql::{EmptyMutation, EmptySubscription, Object, Schema};

struct Query;

#[Object]
impl Query {
    async fn hello(&self) -> &'static str {
        "world"
    }
}

let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
let response = pollster::block_on(ocre::graphql::respond(&schema, br#"{"query": "{ hello }"}"#, ()));
assert_eq!(response.status(), 200);
let body = pollster::block_on(axum::body::to_bytes(response.into_body(), usize::MAX)).unwrap();
assert_eq!(body, r#"{"data":{"hello":"world"}}"#);

let response = pollster::block_on(ocre::graphql::respond(&schema, b"not json", ()));
assert_eq!(response.status(), 400);