|
| 1 | +use apollo_compiler::resolvers::AsyncObjectValue; |
| 2 | +use apollo_compiler::resolvers::AsyncResolvedValue; |
| 3 | +use apollo_compiler::resolvers::Execution; |
| 4 | +use apollo_compiler::resolvers::FieldError; |
| 5 | +use apollo_compiler::resolvers::ResolveInfo; |
| 6 | +use apollo_compiler::ExecutableDocument; |
| 7 | +use apollo_compiler::Schema; |
| 8 | +use futures::future::BoxFuture; |
| 9 | + |
| 10 | +async fn async_resolvers_example() { |
| 11 | + let sdl = " |
| 12 | + type Query { |
| 13 | + field1: String |
| 14 | + field2: [Int] |
| 15 | + } |
| 16 | + "; |
| 17 | + |
| 18 | + struct Query; |
| 19 | + |
| 20 | + impl AsyncObjectValue for Query { |
| 21 | + fn type_name(&self) -> &str { |
| 22 | + "Query" |
| 23 | + } |
| 24 | + |
| 25 | + fn resolve_field<'a>( |
| 26 | + &'a self, |
| 27 | + info: &'a ResolveInfo<'a>, |
| 28 | + ) -> BoxFuture<'a, Result<AsyncResolvedValue<'a>, FieldError>> { |
| 29 | + Box::pin(async move { |
| 30 | + match info.field_name() { |
| 31 | + "field1" => Ok(AsyncResolvedValue::leaf(self.resolve_field1().await)), |
| 32 | + "field2" => Ok(AsyncResolvedValue::list(self.resolve_field2().await)), |
| 33 | + _ => Err(self.unknown_field_error(info)), |
| 34 | + } |
| 35 | + }) |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + impl Query { |
| 40 | + async fn resolve_field1(&self) -> String { |
| 41 | + // totally doing asynchronous I/O here |
| 42 | + "string".into() |
| 43 | + } |
| 44 | + |
| 45 | + async fn resolve_field2(&self) -> [AsyncResolvedValue<'_>; 4] { |
| 46 | + // very await |
| 47 | + [7, 42, 0, 0].map(AsyncResolvedValue::leaf) |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + let query = " |
| 52 | + query($skp: Boolean!) { |
| 53 | + field1 @skip(if: $skp) |
| 54 | + field2 |
| 55 | + } |
| 56 | + "; |
| 57 | + let variables_values = &serde_json_bytes::json!({ |
| 58 | + "skp": false, |
| 59 | + }); |
| 60 | + |
| 61 | + let schema = Schema::parse_and_validate(sdl, "schema.graphql").unwrap(); |
| 62 | + let document = ExecutableDocument::parse_and_validate(&schema, query, "query.graphql").unwrap(); |
| 63 | + let response = Execution::new(&schema, &document) |
| 64 | + .raw_variable_values(variables_values.as_object().unwrap()) |
| 65 | + .execute_async(&Query) |
| 66 | + .await |
| 67 | + .unwrap(); |
| 68 | + let response = serde_json::to_string_pretty(&response).unwrap(); |
| 69 | + expect_test::expect![[r#" |
| 70 | + { |
| 71 | + "data": { |
| 72 | + "field1": "string", |
| 73 | + "field2": [ |
| 74 | + 7, |
| 75 | + 42, |
| 76 | + 0, |
| 77 | + 0 |
| 78 | + ] |
| 79 | + } |
| 80 | + }"#]] |
| 81 | + .assert_eq(&response); |
| 82 | +} |
| 83 | + |
| 84 | +fn main() { |
| 85 | + futures::executor::block_on(async_resolvers_example()) |
| 86 | +} |
0 commit comments