async-graphql / examples

217 stars 54 forks source link

Example of throwing error for missing token via GraphQLResponse #45

Closed rex-remind101 closed 2 years ago

rex-remind101 commented 2 years ago

Hi, if the token is missing I'd like to throw an error by adding it to the errors payload in the response. This example doesn't demonstrate that, do you have another example or could one be added please? Thank you.

sunli829 commented 2 years ago

Do it like this:

async fn index(
    schema: web::Data<TokenSchema>,
    req: HttpRequest,
    gql_request: GraphQLRequest,
) -> Result<GraphQLResponse> {
    let mut request = gql_request.into_inner();
    if let Some(token) = get_token_from_headers(req.headers()) {
        request = request.data(token);
    } else {
        return Err(actix_web::error::ErrorUnauthorized("unauthorized"));
    }
    Ok(schema.execute(request).await.into())
}