async-graphql-tide: use tide Status trait and remove http-types dep
This commit is contained in:
parent
0cf339bc06
commit
a84bb7f671
|
@ -15,7 +15,6 @@ categories = ["network-programming", "asynchronous"]
|
||||||
[dependencies]
|
[dependencies]
|
||||||
async-graphql = { path = "..", version = "1.9.23" }
|
async-graphql = { path = "..", version = "1.9.23" }
|
||||||
tide = "0.8"
|
tide = "0.8"
|
||||||
http-types = "1.2.0"
|
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
async-std = "1.5.0"
|
async-std = "1.5.0"
|
||||||
|
|
|
@ -8,11 +8,10 @@ use async_graphql::http::GQLResponse;
|
||||||
use async_graphql::{
|
use async_graphql::{
|
||||||
IntoQueryBuilder, IntoQueryBuilderOpts, ObjectType, QueryBuilder, Schema, SubscriptionType,
|
IntoQueryBuilder, IntoQueryBuilderOpts, ObjectType, QueryBuilder, Schema, SubscriptionType,
|
||||||
};
|
};
|
||||||
use tide::{Request, Response, StatusCode};
|
use tide::{http::headers, Request, Response, Status, StatusCode};
|
||||||
|
|
||||||
/// GraphQL request handler
|
/// GraphQL request handler
|
||||||
///
|
///
|
||||||
/// It outputs a tuple containing the `Schema` and `QuertBuilder`.
|
|
||||||
///
|
///
|
||||||
/// # Examples
|
/// # Examples
|
||||||
/// *[Full Example](<https://github.com/sunli829/async-graphql-examples/blob/master/tide/starwars/src/main.rs>)*
|
/// *[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,
|
F: Fn(QueryBuilder) -> QueryBuilder,
|
||||||
{
|
{
|
||||||
let content_type = req
|
let content_type = req
|
||||||
.header(&http_types::headers::CONTENT_TYPE)
|
.header(&headers::CONTENT_TYPE)
|
||||||
.and_then(|values| values.first().map(|value| value.to_string()));
|
.and_then(|values| values.first().map(|value| value.to_string()));
|
||||||
|
|
||||||
let mut query_builder = (content_type, req)
|
let mut query_builder = (content_type, req)
|
||||||
.into_query_builder_opts(&opts)
|
.into_query_builder_opts(&opts)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| tide::Error::new(StatusCode::BadRequest, e))?;
|
.status(StatusCode::BadRequest)?;
|
||||||
|
|
||||||
query_builder = query_builder_configuration(query_builder);
|
query_builder = query_builder_configuration(query_builder);
|
||||||
|
|
||||||
|
|
|
@ -7,11 +7,14 @@ use tide::Request;
|
||||||
|
|
||||||
use async_graphql::*;
|
use async_graphql::*;
|
||||||
|
|
||||||
|
type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn quickstart() -> tide::Result<()> {
|
fn quickstart() -> Result<()> {
|
||||||
task::block_on(async {
|
task::block_on(async {
|
||||||
let port = test_utils::find_port().await;
|
let listen_addr = test_utils::find_listen_addr().await;
|
||||||
let server = task::spawn(async move {
|
|
||||||
|
let server: task::JoinHandle<Result<()>> = task::spawn(async move {
|
||||||
struct QueryRoot;
|
struct QueryRoot;
|
||||||
#[Object]
|
#[Object]
|
||||||
impl QueryRoot {
|
impl QueryRoot {
|
||||||
|
@ -26,31 +29,37 @@ fn quickstart() -> tide::Result<()> {
|
||||||
let schema = Schema::build(QueryRoot, EmptyMutation, EmptySubscription).finish();
|
let schema = Schema::build(QueryRoot, EmptyMutation, EmptySubscription).finish();
|
||||||
async_graphql_tide::graphql(req, schema, |query_builder| query_builder).await
|
async_graphql_tide::graphql(req, schema, |query_builder| query_builder).await
|
||||||
});
|
});
|
||||||
app.listen(&port).await?;
|
app.listen(&listen_addr).await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
|
|
||||||
let client = task::spawn(async move {
|
let client: task::JoinHandle<Result<()>> = task::spawn(async move {
|
||||||
task::sleep(Duration::from_millis(100)).await;
|
task::sleep(Duration::from_millis(300)).await;
|
||||||
let string = surf::post(format!("http://{}", port))
|
|
||||||
|
let string = surf::post(format!("http://{}", listen_addr))
|
||||||
.body_bytes(r#"{"query":"{ add(a: 10, b: 20) }"}"#)
|
.body_bytes(r#"{"query":"{ add(a: 10, b: 20) }"}"#)
|
||||||
.set_header("Content-Type".parse().unwrap(), "application/json")
|
.set_header("Content-Type".parse().unwrap(), "application/json")
|
||||||
.recv_string()
|
.recv_string()
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
assert_eq!(string, json!({"data": {"add": 30}}).to_string());
|
assert_eq!(string, json!({"data": {"add": 30}}).to_string());
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
|
|
||||||
server.race(client).await
|
server.race(client).await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn hello() -> tide::Result<()> {
|
fn hello() -> Result<()> {
|
||||||
task::block_on(async {
|
task::block_on(async {
|
||||||
let port = test_utils::find_port().await;
|
let listen_addr = test_utils::find_listen_addr().await;
|
||||||
let server = task::spawn(async move {
|
|
||||||
|
let server: task::JoinHandle<Result<()>> = task::spawn(async move {
|
||||||
struct Hello(String);
|
struct Hello(String);
|
||||||
struct QueryRoot;
|
struct QueryRoot;
|
||||||
#[Object]
|
#[Object]
|
||||||
|
@ -58,22 +67,19 @@ fn hello() -> tide::Result<()> {
|
||||||
#[field(desc = "Returns hello")]
|
#[field(desc = "Returns hello")]
|
||||||
async fn hello<'a>(&self, ctx: &'a Context<'_>) -> String {
|
async fn hello<'a>(&self, ctx: &'a Context<'_>) -> String {
|
||||||
let name = ctx.data_opt::<Hello>().map(|hello| hello.0.as_str());
|
let name = ctx.data_opt::<Hello>().map(|hello| hello.0.as_str());
|
||||||
format!(
|
format!("Hello, {}!", name.unwrap_or("world"))
|
||||||
"Hello, {}!",
|
|
||||||
if let Some(name) = name { name } else { "world" }
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct ServerState {
|
struct AppState {
|
||||||
schema: Schema<QueryRoot, EmptyMutation, EmptySubscription>,
|
schema: Schema<QueryRoot, EmptyMutation, EmptySubscription>,
|
||||||
}
|
}
|
||||||
let schema = Schema::build(QueryRoot, EmptyMutation, EmptySubscription).finish();
|
let schema = Schema::build(QueryRoot, EmptyMutation, EmptySubscription).finish();
|
||||||
|
|
||||||
let server_state = ServerState { schema };
|
let app_state = AppState { schema };
|
||||||
let mut app = tide::with_state(server_state);
|
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 schema = req.state().schema.clone();
|
||||||
let name = &req
|
let name = &req
|
||||||
.header(&"name".parse().unwrap())
|
.header(&"name".parse().unwrap())
|
||||||
|
@ -87,33 +93,39 @@ fn hello() -> tide::Result<()> {
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
});
|
});
|
||||||
app.listen(&port).await?;
|
app.listen(&listen_addr).await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
|
|
||||||
let client = task::spawn(async move {
|
let client: task::JoinHandle<Result<()>> = task::spawn(async move {
|
||||||
task::sleep(Duration::from_millis(100)).await;
|
task::sleep(Duration::from_millis(300)).await;
|
||||||
let string = surf::post(format!("http://{}", port))
|
|
||||||
|
let string = surf::post(format!("http://{}", listen_addr))
|
||||||
.body_bytes(r#"{"query":"{ hello }"}"#)
|
.body_bytes(r#"{"query":"{ hello }"}"#)
|
||||||
.set_header("Content-Type".parse().unwrap(), "application/json")
|
.set_header("Content-Type".parse().unwrap(), "application/json")
|
||||||
.set_header("Name".parse().unwrap(), "Foo")
|
.set_header("Name".parse().unwrap(), "Foo")
|
||||||
.recv_string()
|
.recv_string()
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
assert_eq!(string, json!({"data":{"hello":"Hello, Foo!"}}).to_string());
|
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 }"}"#)
|
.body_bytes(r#"{"query":"{ hello }"}"#)
|
||||||
.set_header("Content-Type".parse().unwrap(), "application/json")
|
.set_header("Content-Type".parse().unwrap(), "application/json")
|
||||||
.recv_string()
|
.recv_string()
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
string,
|
string,
|
||||||
json!({"data":{"hello":"Hello, world!"}}).to_string()
|
json!({"data":{"hello":"Hello, world!"}}).to_string()
|
||||||
);
|
);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
|
|
||||||
server.race(client).await
|
server.race(client).await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
|
@ -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")
|
async_std::net::TcpListener::bind("localhost:0")
|
||||||
.await
|
.await
|
||||||
.unwrap()
|
.unwrap()
|
||||||
|
|
Loading…
Reference in New Issue
Block a user