Merge pull request #36 from vkill/async-graphql-tide2

async-graphql-tide: use tide Status trait and remove http-types dep
This commit is contained in:
Sunli 2020-04-28 00:03:33 +08:00 committed by GitHub
commit adca07c58e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 41 additions and 31 deletions

View File

@ -15,7 +15,6 @@ categories = ["network-programming", "asynchronous"]
[dependencies]
async-graphql = { path = "..", version = "1.9.23" }
tide = "0.8"
http-types = "1.2.0"
[dev-dependencies]
async-std = "1.5.0"

View File

@ -8,11 +8,10 @@ use async_graphql::http::GQLResponse;
use async_graphql::{
IntoQueryBuilder, IntoQueryBuilderOpts, ObjectType, QueryBuilder, Schema, SubscriptionType,
};
use tide::{Request, Response, StatusCode};
use tide::{http::headers, Request, Response, Status, StatusCode};
/// GraphQL request handler
///
/// It outputs a tuple containing the `Schema` and `QuertBuilder`.
///
/// # Examples
/// *[Full Example](<https://github.com/sunli829/async-graphql-examples/blob/master/tide/starwars/src/main.rs>)*
@ -74,13 +73,13 @@ where
F: Fn(QueryBuilder) -> QueryBuilder,
{
let content_type = req
.header(&http_types::headers::CONTENT_TYPE)
.header(&headers::CONTENT_TYPE)
.and_then(|values| values.first().map(|value| value.to_string()));
let mut query_builder = (content_type, req)
.into_query_builder_opts(&opts)
.await
.map_err(|e| tide::Error::new(StatusCode::BadRequest, e))?;
.status(StatusCode::BadRequest)?;
query_builder = query_builder_configuration(query_builder);

View File

@ -7,11 +7,14 @@ use tide::Request;
use async_graphql::*;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
#[test]
fn quickstart() -> tide::Result<()> {
fn quickstart() -> Result<()> {
task::block_on(async {
let port = test_utils::find_port().await;
let server = task::spawn(async move {
let listen_addr = test_utils::find_listen_addr().await;
let server: task::JoinHandle<Result<()>> = task::spawn(async move {
struct QueryRoot;
#[Object]
impl QueryRoot {
@ -26,31 +29,37 @@ fn quickstart() -> tide::Result<()> {
let schema = Schema::build(QueryRoot, EmptyMutation, EmptySubscription).finish();
async_graphql_tide::graphql(req, schema, |query_builder| query_builder).await
});
app.listen(&port).await?;
app.listen(&listen_addr).await?;
Ok(())
});
let client = task::spawn(async move {
task::sleep(Duration::from_millis(100)).await;
let string = surf::post(format!("http://{}", port))
let client: task::JoinHandle<Result<()>> = task::spawn(async move {
task::sleep(Duration::from_millis(300)).await;
let string = surf::post(format!("http://{}", listen_addr))
.body_bytes(r#"{"query":"{ add(a: 10, b: 20) }"}"#)
.set_header("Content-Type".parse().unwrap(), "application/json")
.recv_string()
.await?;
assert_eq!(string, json!({"data": {"add": 30}}).to_string());
Ok(())
});
server.race(client).await
server.race(client).await?;
Ok(())
})
}
#[test]
fn hello() -> tide::Result<()> {
fn hello() -> Result<()> {
task::block_on(async {
let port = test_utils::find_port().await;
let server = task::spawn(async move {
let listen_addr = test_utils::find_listen_addr().await;
let server: task::JoinHandle<Result<()>> = task::spawn(async move {
struct Hello(String);
struct QueryRoot;
#[Object]
@ -58,22 +67,19 @@ fn hello() -> tide::Result<()> {
#[field(desc = "Returns hello")]
async fn hello<'a>(&self, ctx: &'a Context<'_>) -> String {
let name = ctx.data_opt::<Hello>().map(|hello| hello.0.as_str());
format!(
"Hello, {}!",
if let Some(name) = name { name } else { "world" }
)
format!("Hello, {}!", name.unwrap_or("world"))
}
}
struct ServerState {
struct AppState {
schema: Schema<QueryRoot, EmptyMutation, EmptySubscription>,
}
let schema = Schema::build(QueryRoot, EmptyMutation, EmptySubscription).finish();
let server_state = ServerState { schema };
let mut app = tide::with_state(server_state);
let app_state = AppState { schema };
let mut app = tide::with_state(app_state);
app.at("/").post(|req: Request<ServerState>| async move {
app.at("/").post(|req: Request<AppState>| async move {
let schema = req.state().schema.clone();
let name = &req
.header(&"name".parse().unwrap())
@ -87,33 +93,39 @@ fn hello() -> tide::Result<()> {
})
.await
});
app.listen(&port).await?;
app.listen(&listen_addr).await?;
Ok(())
});
let client = task::spawn(async move {
task::sleep(Duration::from_millis(100)).await;
let string = surf::post(format!("http://{}", port))
let client: task::JoinHandle<Result<()>> = task::spawn(async move {
task::sleep(Duration::from_millis(300)).await;
let string = surf::post(format!("http://{}", listen_addr))
.body_bytes(r#"{"query":"{ hello }"}"#)
.set_header("Content-Type".parse().unwrap(), "application/json")
.set_header("Name".parse().unwrap(), "Foo")
.recv_string()
.await?;
assert_eq!(string, json!({"data":{"hello":"Hello, Foo!"}}).to_string());
let string = surf::post(format!("http://{}", port))
let string = surf::post(format!("http://{}", listen_addr))
.body_bytes(r#"{"query":"{ hello }"}"#)
.set_header("Content-Type".parse().unwrap(), "application/json")
.recv_string()
.await?;
assert_eq!(
string,
json!({"data":{"hello":"Hello, world!"}}).to_string()
);
Ok(())
});
server.race(client).await
server.race(client).await?;
Ok(())
})
}

View File

@ -1,4 +1,4 @@
pub async fn find_port() -> async_std::net::SocketAddr {
pub async fn find_listen_addr() -> async_std::net::SocketAddr {
async_std::net::TcpListener::bind("localhost:0")
.await
.unwrap()