Merge pull request #90 from vkill/async-graphql-tide-ext

async-graphql-tide: support make query_builder from get request
This commit is contained in:
Sunli 2020-05-16 10:38:10 +08:00 committed by GitHub
commit 2335aa1f2b
2 changed files with 54 additions and 13 deletions

View File

@ -4,13 +4,16 @@
#![allow(clippy::type_complexity)]
#![allow(clippy::needless_doctest_main)]
use async_graphql::http::GQLResponse;
use async_graphql::http::{GQLRequest, GQLResponse};
use async_graphql::{
IntoQueryBuilder, IntoQueryBuilderOpts, ObjectType, ParseRequestError, QueryBuilder,
QueryResponse, Schema, SubscriptionType,
};
use async_trait::async_trait;
use tide::{http::headers, Request, Response, Status, StatusCode};
use tide::{
http::{headers, Method},
Request, Response, Status, StatusCode,
};
/// GraphQL request handler
///
@ -109,10 +112,19 @@ impl<State: Send + Sync + 'static> RequestExt<State> for Request<State> {
self,
opts: IntoQueryBuilderOpts,
) -> Result<QueryBuilder, ParseRequestError> {
let content_type = self
.header(&headers::CONTENT_TYPE)
.and_then(|values| values.first().map(|value| value.to_string()));
(content_type, self).into_query_builder_opts(&opts).await
if self.method() == Method::Get {
match self.query::<GQLRequest>() {
Ok(gql_request) => gql_request.into_query_builder_opts(&opts).await,
Err(_) => Err(ParseRequestError::Io(std::io::Error::from(
std::io::ErrorKind::InvalidInput,
))),
}
} else {
let content_type = self
.header(&headers::CONTENT_TYPE)
.and_then(|values| values.first().map(|value| value.to_string()));
(content_type, self).into_query_builder_opts(&opts).await
}
}
}

View File

@ -3,10 +3,8 @@ use serde_json::json;
use smol::{Task, Timer};
use std::io::Read;
use std::time::Duration;
use tide::Request;
use async_graphql::*;
use async_graphql_tide::graphql;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
@ -16,6 +14,9 @@ fn quickstart() -> Result<()> {
let listen_addr = test_utils::find_listen_addr().await;
let server = Task::<Result<()>>::spawn(async move {
use async_graphql_tide::{RequestExt, ResponseExt};
use tide::{http::StatusCode, Request, Response, Status};
struct QueryRoot;
#[Object]
impl QueryRoot {
@ -25,11 +26,16 @@ fn quickstart() -> Result<()> {
}
}
let mut app = tide::new();
app.at("/").post(|req: Request<()>| async move {
async fn graphql(req: Request<()>) -> tide::Result<Response> {
let schema = Schema::build(QueryRoot, EmptyMutation, EmptySubscription).finish();
graphql(req, schema, |query_builder| query_builder).await
});
let query_builder = req.body_graphql().await.status(StatusCode::BadRequest)?;
Ok(Response::new(StatusCode::Ok)
.body_graphql(query_builder.execute(&schema).await)
.status(StatusCode::InternalServerError)?)
}
let mut app = tide::new();
app.at("/").post(graphql).get(graphql);
app.listen(&listen_addr).await?;
Ok(())
@ -38,6 +44,7 @@ fn quickstart() -> Result<()> {
let client = Task::<Result<()>>::spawn(async move {
Timer::after(Duration::from_millis(300)).await;
//
let resp = reqwest::Client::new()
.post(format!("http://{}", listen_addr).as_str())
.body(r#"{"query":"{ add(a: 10, b: 20) }"}"#)
@ -47,7 +54,25 @@ fn quickstart() -> Result<()> {
assert_eq!(resp.status(), reqwest::StatusCode::OK);
let string = resp.text().await?;
println!("{}", string);
println!("via post {}", string);
assert_eq!(string, json!({"data": {"add": 30}}).to_string());
//
let resp = reqwest::Client::new()
.get(
format!(
"http://{}?query=%7B%20add%28a%3A%2010%2C%20b%3A%2020%29%20%7D",
listen_addr
)
.as_str(),
)
.send()
.await?;
assert_eq!(resp.status(), reqwest::StatusCode::OK);
let string = resp.text().await?;
println!("via get {}", string);
assert_eq!(string, json!({"data": {"add": 30}}).to_string());
@ -67,6 +92,8 @@ fn hello() -> Result<()> {
let listen_addr = test_utils::find_listen_addr().await;
let server = Task::<Result<()>>::spawn(async move {
use tide::Request;
struct Hello(String);
struct QueryRoot;
#[Object]
@ -154,6 +181,8 @@ fn upload() -> Result<()> {
let listen_addr = test_utils::find_listen_addr().await;
let server = Task::<Result<()>>::spawn(async move {
use tide::Request;
struct QueryRoot;
#[Object]
impl QueryRoot {}