Merge branch 'actix-web-v4-beta' into async-graphql-v3
This commit is contained in:
commit
4bf73df67e
|
@ -13,16 +13,16 @@ categories = ["network-programming", "asynchronous"]
|
|||
|
||||
[dependencies]
|
||||
async-graphql = { path = "../..", version = "=2.11.2" }
|
||||
|
||||
actix = "0.10.0"
|
||||
actix-http = "2.2.0"
|
||||
actix-web = { version = "3.3.2", default-features = false }
|
||||
actix-web-actors = "3.0.0"
|
||||
actix = "0.12.0"
|
||||
actix-http = "3.0.0-beta.11"
|
||||
actix-web = { version = "4.0.0-beta.10", default-features = false }
|
||||
actix-web-actors = "4.0.0-beta.7"
|
||||
async-channel = "1.6.1"
|
||||
futures-util = { version = "0.3.13", default-features = false }
|
||||
futures-util = { version = "0.3.17", default-features = false }
|
||||
serde_json = "1.0.64"
|
||||
serde_urlencoded = "0.7.0"
|
||||
futures-channel = "0.3.13"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "1.1.0"
|
||||
actix-rt = "2.2.0"
|
||||
async-mutex = "1.4.0"
|
||||
|
|
|
@ -3,23 +3,22 @@
|
|||
#![allow(clippy::upper_case_acronyms)]
|
||||
#![warn(missing_docs)]
|
||||
|
||||
mod subscription;
|
||||
|
||||
pub use subscription::WSSubscription;
|
||||
|
||||
use std::future::Future;
|
||||
use std::io::{self, ErrorKind};
|
||||
use std::pin::Pin;
|
||||
|
||||
use actix_web::client::PayloadError;
|
||||
use actix_http::error::PayloadError;
|
||||
use actix_web::dev::{Payload, PayloadStream};
|
||||
use actix_web::http::{Method, StatusCode};
|
||||
use actix_web::{http, Error, FromRequest, HttpRequest, HttpResponse, Responder, Result};
|
||||
use futures_util::future::{self, FutureExt, Ready};
|
||||
use futures_util::future::{self, FutureExt};
|
||||
use futures_util::{StreamExt, TryStreamExt};
|
||||
|
||||
use async_graphql::http::MultipartOptions;
|
||||
use async_graphql::ParseRequestError;
|
||||
pub use subscription::WSSubscription;
|
||||
|
||||
mod subscription;
|
||||
|
||||
/// Extractor for GraphQL request.
|
||||
///
|
||||
|
@ -40,7 +39,6 @@ type BatchToRequestMapper =
|
|||
impl FromRequest for Request {
|
||||
type Error = Error;
|
||||
type Future = future::Map<<BatchRequest as FromRequest>::Future, BatchToRequestMapper>;
|
||||
type Config = MultipartOptions;
|
||||
|
||||
fn from_request(req: &HttpRequest, payload: &mut Payload<PayloadStream>) -> Self::Future {
|
||||
BatchRequest::from_request(req, payload).map(|res| {
|
||||
|
@ -69,10 +67,12 @@ impl BatchRequest {
|
|||
impl FromRequest for BatchRequest {
|
||||
type Error = Error;
|
||||
type Future = Pin<Box<dyn Future<Output = Result<BatchRequest>>>>;
|
||||
type Config = MultipartOptions;
|
||||
|
||||
fn from_request(req: &HttpRequest, payload: &mut Payload<PayloadStream>) -> Self::Future {
|
||||
let config = req.app_data::<Self::Config>().cloned().unwrap_or_default();
|
||||
let config = req
|
||||
.app_data::<MultipartOptions>()
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
|
||||
if req.method() == Method::GET {
|
||||
let res = serde_urlencoded::from_str(req.query_string());
|
||||
|
@ -118,6 +118,7 @@ impl FromRequest for BatchRequest {
|
|||
}
|
||||
PayloadError::Http2Payload(e) if e.is_io() => e.into_io().unwrap(),
|
||||
PayloadError::Http2Payload(e) => io::Error::new(ErrorKind::Other, e),
|
||||
_ => io::Error::new(ErrorKind::Other, e),
|
||||
})
|
||||
.into_async_read(),
|
||||
config,
|
||||
|
@ -160,20 +161,17 @@ impl From<async_graphql::BatchResponse> for Response {
|
|||
}
|
||||
|
||||
impl Responder for Response {
|
||||
type Error = Error;
|
||||
type Future = Ready<Result<HttpResponse>>;
|
||||
|
||||
fn respond_to(self, _req: &HttpRequest) -> Self::Future {
|
||||
fn respond_to(self, _req: &HttpRequest) -> HttpResponse {
|
||||
let mut res = HttpResponse::build(StatusCode::OK);
|
||||
res.content_type("application/json");
|
||||
if self.0.is_ok() {
|
||||
if let Some(cache_control) = self.0.cache_control().value() {
|
||||
res.header("cache-control", cache_control);
|
||||
res.append_header(("cache-control", cache_control));
|
||||
}
|
||||
}
|
||||
for (name, value) in self.0.http_headers() {
|
||||
res.header(name, value);
|
||||
res.append_header((name, value));
|
||||
}
|
||||
futures_util::future::ok(res.body(serde_json::to_string(&self.0).unwrap()))
|
||||
res.body(serde_json::to_string(&self.0).unwrap())
|
||||
}
|
||||
}
|
||||
}
|
|
@ -3,19 +3,20 @@ use std::str::FromStr;
|
|||
use std::time::{Duration, Instant};
|
||||
|
||||
use actix::{
|
||||
Actor, ActorContext, ActorFuture, ActorStream, AsyncContext, ContextFutureSpawner,
|
||||
StreamHandler, WrapFuture, WrapStream,
|
||||
Actor, ActorContext, AsyncContext, ContextFutureSpawner, StreamHandler, WrapFuture, WrapStream,
|
||||
};
|
||||
use actix::{ActorFutureExt, ActorStreamExt};
|
||||
use actix_http::error::PayloadError;
|
||||
use actix_http::{ws, Error};
|
||||
use actix_http::ws;
|
||||
use actix_web::web::Bytes;
|
||||
use actix_web::{HttpRequest, HttpResponse};
|
||||
use actix_web_actors::ws::{CloseReason, Message, ProtocolError, WebsocketContext};
|
||||
use async_graphql::http::{WebSocket, WebSocketProtocols, WsMessage, ALL_WEBSOCKET_PROTOCOLS};
|
||||
use async_graphql::{Data, ObjectType, Result, Schema, SubscriptionType};
|
||||
use futures_util::future::Ready;
|
||||
use futures_util::stream::Stream;
|
||||
|
||||
use async_graphql::http::{WebSocket, WebSocketProtocols, WsMessage, ALL_WEBSOCKET_PROTOCOLS};
|
||||
use async_graphql::{Data, ObjectType, Result, Schema, SubscriptionType};
|
||||
|
||||
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
|
||||
const CLIENT_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
|
@ -41,7 +42,7 @@ where
|
|||
schema: Schema<Query, Mutation, Subscription>,
|
||||
request: &HttpRequest,
|
||||
stream: T,
|
||||
) -> Result<HttpResponse, Error>
|
||||
) -> Result<HttpResponse, actix_web::error::Error>
|
||||
where
|
||||
T: Stream<Item = Result<Bytes, PayloadError>> + 'static,
|
||||
{
|
||||
|
@ -65,7 +66,7 @@ where
|
|||
request: &HttpRequest,
|
||||
stream: T,
|
||||
initializer: F,
|
||||
) -> Result<HttpResponse, Error>
|
||||
) -> Result<HttpResponse, actix_web::error::Error>
|
||||
where
|
||||
T: Stream<Item = Result<Bytes, PayloadError>> + 'static,
|
||||
F: FnOnce(serde_json::Value) -> R + Unpin + Send + 'static,
|
||||
|
@ -190,7 +191,7 @@ where
|
|||
Some(std::mem::take(&mut self.continuation))
|
||||
}
|
||||
},
|
||||
Message::Text(s) => Some(s.into_bytes()),
|
||||
Message::Text(s) => Some(s.into_bytes().to_vec()),
|
||||
Message::Binary(bytes) => Some(bytes.to_vec()),
|
||||
Message::Close(_) => {
|
||||
ctx.stop();
|
||||
|
@ -211,4 +212,4 @@ where
|
|||
.spawn(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,137 +1,244 @@
|
|||
mod test_utils;
|
||||
use actix_web::{guard, test, web, App};
|
||||
use async_graphql::*;
|
||||
use actix_http::Method;
|
||||
use actix_web::dev::{AnyBody, Service};
|
||||
use actix_web::{guard, test, web, web::Data, App};
|
||||
use serde_json::json;
|
||||
|
||||
use async_graphql::*;
|
||||
use test_utils::*;
|
||||
|
||||
mod test_utils;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_playground() {
|
||||
let srv = test::start(|| {
|
||||
let srv = test::init_service(
|
||||
App::new().service(
|
||||
web::resource("/")
|
||||
.guard(guard::Get())
|
||||
.to(test_utils::gql_playgound),
|
||||
)
|
||||
});
|
||||
let mut response = srv.get("/").send().await.unwrap();
|
||||
),
|
||||
)
|
||||
.await;
|
||||
let req = test::TestRequest::with_uri("/").to_request();
|
||||
let response = srv.call(req).await.unwrap();
|
||||
assert!(response.status().is_success());
|
||||
let body = response.body().await.unwrap();
|
||||
assert!(std::str::from_utf8(&body).unwrap().contains("graphql"));
|
||||
let body = response.response().body();
|
||||
if let AnyBody::Bytes(bytes) = body {
|
||||
assert!(std::str::from_utf8(&bytes).unwrap().contains("graphql"));
|
||||
} else {
|
||||
panic!("response body must be Bytes {:?}", body);
|
||||
}
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_add() {
|
||||
let srv = test::start(|| {
|
||||
let srv = test::init_service(
|
||||
App::new()
|
||||
.data(Schema::new(AddQueryRoot, EmptyMutation, EmptySubscription))
|
||||
.app_data(Data::new(Schema::new(
|
||||
AddQueryRoot,
|
||||
EmptyMutation,
|
||||
EmptySubscription,
|
||||
)))
|
||||
.service(
|
||||
web::resource("/")
|
||||
.guard(guard::Post())
|
||||
.to(gql_handle_schema::<AddQueryRoot, EmptyMutation, EmptySubscription>),
|
||||
)
|
||||
});
|
||||
let mut response = srv
|
||||
.post("/")
|
||||
.send_body(r#"{"query":"{ add(a: 10, b: 20) }"}"#)
|
||||
),
|
||||
)
|
||||
.await;
|
||||
let response = srv
|
||||
.call(
|
||||
test::TestRequest::with_uri("/")
|
||||
.method(Method::POST)
|
||||
.set_payload(r#"{"query":"{ add(a: 10, b: 20) }"}"#)
|
||||
.to_request(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(response.status().is_success());
|
||||
let body = response.body().await.unwrap();
|
||||
assert_eq!(body, json!({"data": {"add": 30}}).to_string());
|
||||
let body = response.response().body();
|
||||
assert_eq!(
|
||||
body,
|
||||
&AnyBody::Bytes(json!({"data": {"add": 30}}).to_string().into_bytes().into())
|
||||
);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_hello() {
|
||||
let srv = test::start(|| {
|
||||
let srv = test::init_service(
|
||||
App::new()
|
||||
.data(Schema::new(
|
||||
.app_data(Data::new(Schema::new(
|
||||
HelloQueryRoot,
|
||||
EmptyMutation,
|
||||
EmptySubscription,
|
||||
))
|
||||
)))
|
||||
.service(
|
||||
web::resource("/")
|
||||
.guard(guard::Post())
|
||||
.to(gql_handle_schema::<HelloQueryRoot, EmptyMutation, EmptySubscription>),
|
||||
)
|
||||
});
|
||||
),
|
||||
)
|
||||
.await;
|
||||
|
||||
let mut response = srv
|
||||
.post("/")
|
||||
.send_body(r#"{"query":"{ hello }"}"#)
|
||||
let response = srv
|
||||
.call(
|
||||
test::TestRequest::with_uri("/")
|
||||
.method(Method::POST)
|
||||
.set_payload(r#"{"query":"{ hello }"}"#)
|
||||
.to_request(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(response.status().is_success());
|
||||
let body = response.body().await.unwrap();
|
||||
let body = response.response().body();
|
||||
assert_eq!(
|
||||
body,
|
||||
json!({"data": {"hello": "Hello, world!"}}).to_string()
|
||||
&AnyBody::Bytes(
|
||||
json!({"data": {"hello": "Hello, world!"}})
|
||||
.to_string()
|
||||
.into_bytes()
|
||||
.into()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_hello_header() {
|
||||
let srv = test::start(|| {
|
||||
let srv = test::init_service(
|
||||
App::new()
|
||||
.data(Schema::new(
|
||||
.app_data(Data::new(Schema::new(
|
||||
HelloQueryRoot,
|
||||
EmptyMutation,
|
||||
EmptySubscription,
|
||||
))
|
||||
)))
|
||||
.service(
|
||||
web::resource("/")
|
||||
.guard(guard::Post())
|
||||
.to(gql_handle_schema_with_header::<HelloQueryRoot>),
|
||||
)
|
||||
});
|
||||
),
|
||||
)
|
||||
.await;
|
||||
|
||||
let mut response = srv
|
||||
.post("/")
|
||||
.header("Name", "Foo")
|
||||
.send_body(r#"{"query":"{ hello }"}"#)
|
||||
let response = srv
|
||||
.call(
|
||||
test::TestRequest::with_uri("/")
|
||||
.method(Method::POST)
|
||||
.insert_header(("Name", "Foo"))
|
||||
.set_payload(r#"{"query":"{ hello }"}"#)
|
||||
.to_request(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(response.status().is_success());
|
||||
let body = response.body().await.unwrap();
|
||||
assert_eq!(body, json!({"data": {"hello": "Hello, Foo!"}}).to_string());
|
||||
let body = response.response().body();
|
||||
assert_eq!(
|
||||
body,
|
||||
&AnyBody::Bytes(
|
||||
json!({"data": {"hello": "Hello, Foo!"}})
|
||||
.to_string()
|
||||
.into_bytes()
|
||||
.into()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_count() {
|
||||
let srv = test::start(|| {
|
||||
let srv = test::init_service(
|
||||
App::new()
|
||||
.data(
|
||||
.app_data(Data::new(
|
||||
Schema::build(CountQueryRoot, CountMutation, EmptySubscription)
|
||||
.data(Count::default())
|
||||
.finish(),
|
||||
)
|
||||
))
|
||||
.service(
|
||||
web::resource("/")
|
||||
.guard(guard::Post())
|
||||
.to(gql_handle_schema::<CountQueryRoot, CountMutation, EmptySubscription>),
|
||||
)
|
||||
});
|
||||
count_action_helper(0, r#"{"query":"{ count }"}"#, &srv).await;
|
||||
count_action_helper(10, r#"{"query":"mutation{ addCount(count: 10) }"}"#, &srv).await;
|
||||
count_action_helper(
|
||||
8,
|
||||
r#"{"query":"mutation{ subtractCount(count: 2) }"}"#,
|
||||
&srv,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
count_action_helper(
|
||||
6,
|
||||
r#"{"query":"mutation{ subtractCount(count: 2) }"}"#,
|
||||
&srv,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn count_action_helper(expected: i32, body: &'static str, srv: &test::TestServer) {
|
||||
let mut response = srv.post("/").send_body(body).await.unwrap();
|
||||
let response = srv
|
||||
.call(
|
||||
test::TestRequest::with_uri("/")
|
||||
.method(Method::POST)
|
||||
.set_payload(r#"{"query":"{ count }"}"#)
|
||||
.to_request(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(response.status().is_success());
|
||||
let body = response.body().await.unwrap();
|
||||
assert!(std::str::from_utf8(&body)
|
||||
.unwrap()
|
||||
.contains(&expected.to_string()));
|
||||
}
|
||||
let body = response.response().body();
|
||||
assert_eq!(
|
||||
body,
|
||||
&AnyBody::Bytes(
|
||||
json!({"data": {"count": 0}})
|
||||
.to_string()
|
||||
.into_bytes()
|
||||
.into()
|
||||
)
|
||||
);
|
||||
|
||||
let response = srv
|
||||
.call(
|
||||
test::TestRequest::with_uri("/")
|
||||
.method(Method::POST)
|
||||
.set_payload(r#"{"query":"mutation{ addCount(count: 10) }"}"#)
|
||||
.to_request(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(response.status().is_success());
|
||||
let body = response.response().body();
|
||||
assert_eq!(
|
||||
body,
|
||||
&AnyBody::Bytes(
|
||||
json!({"data": {"addCount": 10}})
|
||||
.to_string()
|
||||
.into_bytes()
|
||||
.into()
|
||||
)
|
||||
);
|
||||
|
||||
let response = srv
|
||||
.call(
|
||||
test::TestRequest::with_uri("/")
|
||||
.method(Method::POST)
|
||||
.set_payload(r#"{"query":"mutation{ subtractCount(count: 2) }"}"#)
|
||||
.to_request(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(response.status().is_success());
|
||||
let body = response.response().body();
|
||||
assert_eq!(
|
||||
body,
|
||||
&AnyBody::Bytes(
|
||||
json!({"data": {"subtractCount": 8}})
|
||||
.to_string()
|
||||
.into_bytes()
|
||||
.into()
|
||||
)
|
||||
);
|
||||
|
||||
let response = srv
|
||||
.call(
|
||||
test::TestRequest::with_uri("/")
|
||||
.method(Method::POST)
|
||||
.set_payload(r#"{"query":"mutation{ subtractCount(count: 2) }"}"#)
|
||||
.to_request(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(response.status().is_success());
|
||||
let body = response.response().body();
|
||||
assert_eq!(
|
||||
body,
|
||||
&AnyBody::Bytes(
|
||||
json!({"data": {"subtractCount": 6}})
|
||||
.to_string()
|
||||
.into_bytes()
|
||||
.into()
|
||||
)
|
||||
);
|
||||
}
|
Loading…
Reference in New Issue
Block a user