async-graphql/tests/interface.rs
Koxiaet 50009b66ce Rework errors
This completely overhauls the error system used in async-graphql.
- `Error` has been renamed to `ServerError` and `FieldError` has been
renamed to just `Error`. This is because `FieldError` is by far the most
common error that users will have to use so it makes sense to use the
most obvious error name. Also, the current name didn't make sense as it
was used for things other than field errors, such as the data callback
for websockets.
- `ServerError` has been made completely opaque. Before it was an enum
of all the possible errors, but now it just contains an error message,
the locations, the path and extensions. It is a shame that we lose
information, it makes more sense as _conceptually_ GraphQL does not
provide that information. It also frees us to change the internals of
async-graphql a lot more.
- The path of errors is no longer an opaque JSON value but a regular
type, `Vec<PathSegment>`. The type duplication of `PathSegment` and
`QueryPathSegment` is unfortunate, I plan to work on this in the future.
- Now that `ServerError` is opaque, `RuleError` has been removed from
the public API, making it simpler.
- Additionally `QueryError` has been completely removed. Instead the
error messages are constructed ad-hoc; I took care to never repeat an
error message.
- Instead of constructing field-not-found errors inside the
implementations of field resolvers they now return `Option`s, where a
`None` value is representative of the field not being found.
- As an unfortunate consequence of the last change, self-referential
types based on the output of a subscription resolver can no longer be
created. This does not mean anything for users, but causes lifetime
issues in the implementation of merged objects. I fixed it with a bit of
a hack, but this'll have to be looked into further.
- `InputValueError` now has a generic parameter - it's kind of weird but
it's necessary for ergonomics. It also improves error messages.
- The `ErrorExtensions` trait has been removed. I didn't think the
`extend` method was necessary since `From` impls exist. But the
ergonomics are still there with a new trait `ExtendError`, which
is implemented for both errors and results.
- `Response` now supports serializing multiple errors. This allows for
nice things like having multiple validation errors not be awkwardly
shoved into a single error.
- When an error occurs in execution, data is sent as `null`. This is
slightly more compliant with the spec but the algorithm described in
<https://spec.graphql.org/June2018/#sec-Errors-and-Non-Nullability> has
yet to be implemented.
2020-09-29 20:06:44 +01:00

334 lines
6.7 KiB
Rust

use async_graphql::*;
#[async_std::test]
pub async fn test_interface_simple_object() {
#[derive(SimpleObject)]
struct MyObj {
id: i32,
title: String,
}
#[derive(Interface)]
#[graphql(field(name = "id", type = "&i32"))]
enum Node {
MyObj(MyObj),
}
struct Query;
#[Object]
impl Query {
async fn node(&self) -> Node {
MyObj {
id: 33,
title: "haha".to_string(),
}
.into()
}
}
let query = r#"{
node {
... on Node {
id
}
}
}"#;
let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
assert_eq!(
schema.execute(query).await.into_result().unwrap().data,
serde_json::json!({
"node": {
"id": 33,
}
})
);
}
#[async_std::test]
pub async fn test_interface_simple_object2() {
#[derive(SimpleObject)]
struct MyObj {
id: i32,
title: String,
}
#[derive(Interface)]
#[graphql(field(name = "id", type = "&i32"))]
enum Node {
MyObj(MyObj),
}
struct Query;
#[Object]
impl Query {
async fn node(&self) -> Node {
MyObj {
id: 33,
title: "haha".to_string(),
}
.into()
}
}
let query = r#"{
node {
... on Node {
id
}
}
}"#;
let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
assert_eq!(
schema.execute(query).await.into_result().unwrap().data,
serde_json::json!({
"node": {
"id": 33,
}
})
);
}
#[async_std::test]
pub async fn test_multiple_interfaces() {
struct MyObj;
#[Object]
impl MyObj {
async fn value_a(&self) -> i32 {
1
}
async fn value_b(&self) -> i32 {
2
}
async fn value_c(&self) -> i32 {
3
}
}
#[derive(Interface)]
#[graphql(field(name = "value_a", type = "i32"))]
enum InterfaceA {
MyObj(MyObj),
}
#[derive(Interface)]
#[graphql(field(name = "value_b", type = "i32"))]
enum InterfaceB {
MyObj(MyObj),
}
struct Query;
#[Object]
impl Query {
async fn my_obj(&self) -> InterfaceB {
MyObj.into()
}
}
let schema = Schema::build(Query, EmptyMutation, EmptySubscription)
.register_type::<InterfaceA>() // `InterfaceA` is not directly referenced, so manual registration is required.
.finish();
let query = r#"{
myObj {
... on InterfaceA {
valueA
}
... on InterfaceB {
valueB
}
... on MyObj {
valueC
}
}
}"#;
assert_eq!(
schema.execute(query).await.into_result().unwrap().data,
serde_json::json!({
"myObj": {
"valueA": 1,
"valueB": 2,
"valueC": 3,
}
})
);
}
#[async_std::test]
pub async fn test_multiple_objects_in_multiple_interfaces() {
struct MyObjOne;
#[Object]
impl MyObjOne {
async fn value_a(&self) -> i32 {
1
}
async fn value_b(&self) -> i32 {
2
}
async fn value_c(&self) -> i32 {
3
}
}
struct MyObjTwo;
#[Object]
impl MyObjTwo {
async fn value_a(&self) -> i32 {
1
}
}
#[derive(Interface)]
#[graphql(field(name = "value_a", type = "i32"))]
enum InterfaceA {
MyObjOne(MyObjOne),
MyObjTwo(MyObjTwo),
}
#[derive(Interface)]
#[graphql(field(name = "value_b", type = "i32"))]
enum InterfaceB {
MyObjOne(MyObjOne),
}
struct Query;
#[Object]
impl Query {
async fn my_obj(&self) -> Vec<InterfaceA> {
vec![MyObjOne.into(), MyObjTwo.into()]
}
}
let schema = Schema::build(Query, EmptyMutation, EmptySubscription)
.register_type::<InterfaceB>() // `InterfaceB` is not directly referenced, so manual registration is required.
.finish();
let query = r#"{
myObj {
... on InterfaceA {
valueA
}
... on InterfaceB {
valueB
}
... on MyObjOne {
valueC
}
}
}"#;
assert_eq!(
schema.execute(query).await.into_result().unwrap().data,
serde_json::json!({
"myObj": [{
"valueA": 1,
"valueB": 2,
"valueC": 3,
}, {
"valueA": 1
}]
})
);
}
#[async_std::test]
pub async fn test_interface_field_result() {
struct MyObj;
#[Object]
impl MyObj {
async fn value(&self) -> Result<i32> {
Ok(10)
}
}
#[derive(Interface)]
#[graphql(field(name = "value", type = "Result<i32>"))]
enum Node {
MyObj(MyObj),
}
struct Query;
#[Object]
impl Query {
async fn node(&self) -> Node {
MyObj.into()
}
}
let query = r#"{
node {
... on Node {
value
}
}
}"#;
let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
assert_eq!(
schema.execute(query).await.into_result().unwrap().data,
serde_json::json!({
"node": {
"value": 10,
}
})
);
}
#[async_std::test]
pub async fn test_interface_field_method() {
struct A;
#[Object]
impl A {
#[field(name = "created_at")]
pub async fn created_at(&self) -> i32 {
1
}
}
struct B;
#[Object]
impl B {
#[field(name = "created_at")]
pub async fn created_at(&self) -> i32 {
2
}
}
#[derive(Interface)]
#[graphql(field(name = "created_at", method = "created_at", type = "i32"))]
enum MyInterface {
A(A),
B(B),
}
struct Query;
#[Object]
impl Query {
async fn test(&self) -> MyInterface {
A.into()
}
}
let query = "{ test { created_at } }";
let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
assert_eq!(
schema.execute(query).await.into_result().unwrap().data,
serde_json::json!({
"test": {
"created_at": 1,
}
})
);
}