async-graphql / examples

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Example of throwing error for missing token via GraphQLResponse

rex-remind101 opened this issue · comments

commented

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.

commented

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())
}