Skip to content

Commit

Permalink
correct doc examples so they compile
Browse files Browse the repository at this point in the history
- examples to fix still
  - error_extensions.md ResultExt example does not compile!
     - trait ErrorExtensions is not implemented for ParseIntError
  - dataloader
     - requires sqlx to work. So we either "stub" it OR we rewrite them simpler to use a  simple "faux" db library
  • Loading branch information
urkle committed Jun 2, 2022
1 parent f99204d commit d0f7097
Show file tree
Hide file tree
Showing 64 changed files with 943 additions and 131 deletions.
24 changes: 16 additions & 8 deletions docs/en/src/apollo_federation.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,27 @@
## Entity lookup function

```rust
# extern crate async_graphql;
# use async_graphql::*;
# #[derive(SimpleObject)]
# struct User { id: ID }
struct Query;

#[Object]
impl Query {
#[entity]
#[graphql(entity)]
async fn find_user_by_id(&self, id: ID) -> User {
User { ... }
User { id }
}

#[entity]
#[graphql(entity)]
async fn find_user_by_id_with_username(&self, #[graphql(key)] id: ID, username: String) -> User {
User { ... }
User { id }
}

#[entity]
#[graphql(entity)]
async fn find_user_by_id_and_username(&self, id: ID, username: String) -> User {
User { ... }
User { id }
}
}
```
Expand Down Expand Up @@ -59,6 +63,10 @@ A single primary key can consist of multiple fields, and even nested fields, you
In the following example, the primary key of the `User` object is `key { a b }`.

```rust
# extern crate async_graphql;
# use async_graphql::*;
# #[derive(SimpleObject)]
# struct User { id: i32 }
#[derive(InputObject)]
struct NestedKey {
a: i32,
Expand All @@ -69,9 +77,9 @@ struct Query;

#[Object]
impl Query {
#[entity]
#[graphql(entity)]
async fn find_user_by_key(&self, key: NestedKey) -> User {
User { ... }
User { id: key.a }
}
}
```
5 changes: 5 additions & 0 deletions docs/en/src/apollo_tracing.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,14 @@ Apollo Tracing provides performance analysis results for each step of query. Thi
To enable the Apollo Tracing extension, add the extension when the `Schema` is created.

```rust
# extern crate async_graphql;
use async_graphql::*;
use async_graphql::extensions::ApolloTracing;

# struct Query;
# #[Object]
# impl Query { async fn version(&self) -> &str { "1.0" } }

let schema = Schema::build(Query, EmptyMutation, EmptySubscription)
.extension(ApolloTracing) // Enable ApolloTracing extension
.finish();
Expand Down
7 changes: 6 additions & 1 deletion docs/en/src/cache_control.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,23 @@ when querying multiple resolvers, the results of all cache control parameters wi
We can use `QueryResponse` to get a merged cache control result from a query result, and call `CacheControl::value` to get the corresponding HTTP header.

```rust
# extern crate async_graphql;
# use async_graphql::*;
# struct Query;
#[Object(cache_control(max_age = 60))]
impl Query {
#[graphql(cache_control(max_age = 30))]
async fn value1(&self) -> i32 {
1
}

#[graphql(cache_control(private))]
async fn value2(&self) -> i32 {
2
}

async fn value3(&self) -> i32 {
3
}
}
```
Expand All @@ -46,4 +52,3 @@ The following are different queries corresponding to different cache control res
# max_age=60
{ value3 }
```

44 changes: 35 additions & 9 deletions docs/en/src/context.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ You can request the data inside a query by just calling `ctx.data::<TypeOfYourDa
The following example shows how to borrow data in `Context`.

```rust
# extern crate async_graphql;
use async_graphql::*;

struct Query;
Expand All @@ -32,12 +33,22 @@ impl Query {

### Schema data

You can put data inside the context at the creation of the schema, it's usefull for data that do not change, like a connection pool.
You can put data inside the context at the creation of the schema, it's useful for data that do not change, like a connection pool.

An instance of how it would be written inside an application:

```rust
let schema = Schema::build(Query::default(), Mutation::default(), EmptySubscription)
# extern crate async_graphql;
# use async_graphql::*;
# #[derive(Default,SimpleObject)]
# struct Query { version: i32}
# struct EnvStruct;
# let env_struct = EnvStruct;
# struct S3Object;
# let s3_storage = S3Object;
# struct DBConnection;
# let db_core = DBConnection;
let schema = Schema::build(Query::default(), EmptyMutation, EmptySubscription)
.data(env_struct)
.data(s3_storage)
.data(db_core)
Expand All @@ -51,22 +62,31 @@ You can put data inside the context at the execution of the request, it's useful
A little example with a `warp` route:

```rust
# extern crate async_graphql;
# extern crate async_graphql_warp;
# extern crate warp;
# use async_graphql::*;
# use warp::{Filter, Reply};
# use std::convert::Infallible;
# #[derive(Default, SimpleObject)]
# struct Query { name: String }
# struct AuthInfo { pub token: Option<String> }
# let schema = Schema::build(Query::default(), EmptyMutation, EmptySubscription).finish();
# let schema_filter = async_graphql_warp::graphql(schema);
let graphql_post = warp::post()
.and(warp::path("graphql"))
.and(warp::header::optional("Authorization"))
.and(schema_filter)
.and(a_warp_filter)
...
.and_then( |schema: (Schema<Query, Mutation, Subscriptions>, async_graphql::Request), arg2: ArgType2 ...| async move {
let (schema, request) = schema;
let your_auth_data = auth_function_from_headers(headers).await?;
.and_then( |auth: Option<String>, (schema, mut request): (Schema<Query, EmptyMutation, EmptySubscription>, async_graphql::Request)| async move {
// Do something to get auth data from the header
let your_auth_data = AuthInfo { token: auth };
let response = schema
.execute(
request
.data(your_auth_data)
.data(something_else)
).await;

Ok(async_graphql_warp::Response::from(response))
Ok::<_, Infallible>(async_graphql_warp::GraphQLResponse::from(response))
});
```

Expand All @@ -75,6 +95,11 @@ let graphql_post = warp::post()
With the Context you can also insert and appends headers.

```rust
# extern crate async_graphql;
# extern crate http;
# use ::http::header::ACCESS_CONTROL_ALLOW_ORIGIN;
# use async_graphql::*;
# struct Query;
#[Object]
impl Query {
async fn greet(&self, ctx: &Context<'_>) -> String {
Expand All @@ -101,6 +126,7 @@ Sometimes you want to know what fields are requested in the subquery to optimize
If you want to perform a search accross the query or the subqueries, you do not have to do this by hand with the `SelectionField`, you can use the `ctx.look_ahead()` to perform a selection

```rust
# extern crate async_graphql;
use async_graphql::*;

#[derive(SimpleObject)]
Expand Down
9 changes: 5 additions & 4 deletions docs/en/src/cursor_connections.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ Relay's cursor connection specification is designed to provide a consistent meth
Defining a cursor connection in `async-graphql` is very simple, you just call the `connection::query` function and query data in the closure.

```rust
# extern crate async_graphql;
use async_graphql::*;
use async_graphql::types::connection::*;

Expand Down Expand Up @@ -34,10 +35,10 @@ impl Query {
let mut connection = Connection::new(start > 0, end < 10000);
connection.edges.extend(
(start..end).into_iter().map(|n|
Ok(Edge::with_additional_fields(n, n as i32, EmptyFields)),
))?;
Ok(connection)
})
Edge::with_additional_fields(n, n as i32, EmptyFields)
));
Ok::<_, async_graphql::Error>(connection)
}).await
}
}

Expand Down
14 changes: 14 additions & 0 deletions docs/en/src/custom_directive.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ generate a factory function that receives the parameters of the directive and re
Currently `Async-graphql` only supports directive located at `FIELD`.

```rust
# extern crate async_graphql;
# use async_graphql::*;
struct ConcatDirective {
value: String,
}
Expand All @@ -33,6 +35,18 @@ fn concat(value: String) -> impl CustomDirective {
Register the directive when building the schema:

```rust
# extern crate async_graphql;
# use async_graphql::*;
# struct Query;
# #[Object]
# impl Query { async fn verison(&self) -> &str { "1.0" } }
# struct ConcatDirective { value: String, }
# #[async_trait::async_trait]
# impl CustomDirective for ConcatDirective {
# async fn resolve_field(&self, _ctx: &Context<'_>, resolve: ResolveFut<'_>) -> ServerResult<Option<Value>> { todo!() }
# }
# #[Directive(location = "field")]
# fn concat(value: String) -> impl CustomDirective { ConcatDirective { value } }
let schema = Schema::build(Query, EmptyMutation, EmptySubscription)
.directive(concat)
.finish();
Expand Down
6 changes: 6 additions & 0 deletions docs/en/src/custom_scalars.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ Using `async-graphql::Scalar`, you can add support for a scalar when you impleme
The following example defines a 64-bit integer scalar where its input and output are strings.

```rust
# extern crate async_graphql;
use async_graphql::*;

struct StringNumber(i64);
Expand Down Expand Up @@ -34,6 +35,11 @@ impl ScalarType for StringNumber {
If your type implemented `serde::Serialize` and `serde::Deserialize`, then you can use this macro to define a scalar more simply.

```rust
# extern crate async_graphql;
# extern crate serde;
# use async_graphql::*;
# use serde::{Serialize, Deserialize};
# use std::collections::HashMap;
#[derive(Serialize, Deserialize)]
struct MyValue {
a: i32,
Expand Down
8 changes: 5 additions & 3 deletions docs/en/src/dataloader.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ query { todos { users { name } } }

and `User` resolver is like this:

```rust
```rust,ignore
struct User {
id: u64,
}
Expand Down Expand Up @@ -65,7 +65,7 @@ We need to group queries and exclude duplicate queries. `Dataloader` can do this

The following is an example of using `DataLoader` to optimize queries::

```rust
```rust,ignore
use async_graphql::*;
use async_graphql::dataloader::*;
use itertools::Itertools;
Expand Down Expand Up @@ -115,7 +115,9 @@ SELECT name FROM user WHERE id IN (1, 2, 3, 4)

You can implement multiple data types for the same `Loader`, like this:

```rust
```rust,ignore
# extern crate async_graphql;
# use async_graphql::*;
struct PostgresLoader {
pool: sqlx::Pool<Postgres>,
}
Expand Down
26 changes: 19 additions & 7 deletions docs/en/src/default_value.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ Below are some examples.
## Object field

```rust
# extern crate async_graphql;
use async_graphql::*;

struct Query;
Expand All @@ -17,26 +18,35 @@ fn my_default() -> i32 {
#[Object]
impl Query {
// The default value of the value parameter is 0, it will call i32::default()
fn test1(&self, #[graphql(default)] value: i32) {}
async fn test1(&self, #[graphql(default)] value: i32) -> i32 { todo!() }

// The default value of the value parameter is 10
fn test2(&self, #[graphql(default = 10)] value: i32) {}

async fn test2(&self, #[graphql(default = 10)] value: i32) -> i32 { todo!() }
// The default value of the value parameter uses the return result of the my_default function, the value is 30.
fn test3(&self, #[graphql(default_with = "my_default()")] value: i32) {}
async fn test3(&self, #[graphql(default_with = "my_default()")] value: i32) -> i32 { todo!() }
}
```

## Interface field

```rust
# extern crate async_graphql;
# fn my_default() -> i32 { 5 }
# struct MyObj;
# #[Object]
# impl MyObj {
# async fn test1(&self, value: i32) -> i32 { todo!() }
# async fn test2(&self, value: i32) -> i32 { todo!() }
# async fn test3(&self, value: i32) -> i32 { todo!() }
# }
use async_graphql::*;

#[derive(Interface)]
#[graphql(
field(name = "test1", arg(name = "value", default)),
field(name = "test2", arg(name = "value", default = 10)),
field(name = "test3", arg(name = "value", default_with = "my_default()")),
field(name = "test1", type = "i32", arg(name = "value", type = "i32", default)),
field(name = "test2", type = "i32", arg(name = "value", type = "i32", default = 10)),
field(name = "test3", type = "i32", arg(name = "value", type = "i32", default_with = "my_default()")),
)]
enum MyInterface {
MyObj(MyObj),
Expand All @@ -46,6 +56,8 @@ enum MyInterface {
## Input object field

```rust
# extern crate async_graphql;
# fn my_default() -> i32 { 5 }
use async_graphql::*;

#[derive(InputObject)]
Expand Down
10 changes: 10 additions & 0 deletions docs/en/src/define_complex_object.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,16 @@ When creating your `Schema`, you can use `SchemaBuilder::data` to configure the
The following `value_from_db` function shows how to retrieve a database connection from `Context`.

```rust
# extern crate async_graphql;
# struct Data { pub name: String }
# struct DbConn {}
# impl DbConn {
# fn query_something(&self, id: i64) -> std::result::Result<Data, String> { Ok(Data {name:"".into()})}
# }
# struct DbPool {}
# impl DbPool {
# fn take(&self) -> DbConn { DbConn {} }
# }
use async_graphql::*;

struct MyObject {
Expand Down
6 changes: 6 additions & 0 deletions docs/en/src/define_enum.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ It's easy to define an `Enum`, here we have an example:
**Async-graphql will automatically change the name of each item to GraphQL's CONSTANT_CASE convention. You can use `name` to rename.**

```rust
# extern crate async_graphql;
use async_graphql::*;

/// One of the films in the Star Wars Trilogy
Expand All @@ -30,6 +31,8 @@ expose remote enumeration types to GraphQL. In order to provide an `Enum` type,
enum that has parity with the existing, remote enum type.

```rust
# extern crate async_graphql;
# mod remote_crate { pub enum RemoteEnum { A, B, C } }
use async_graphql::*;

/// Provides parity with a remote enum type
Expand All @@ -55,6 +58,9 @@ impl From<remote_crate::RemoteEnum> for LocalEnum {
The process is tedious and requires multiple steps to keep the local and remote enums in sync. `Async_graphql` provides a handy feature to generate the `From<remote_crate::RemoteEnum> for LocalEnum` as well as an opposite direction of `From<LocalEnum> for remote_crate::RemoteEnum` via an additional attribute after deriving `Enum`:

```rust
# extern crate async_graphql;
# use async_graphql::*;
# mod remote_crate { pub enum RemoteEnum { A, B, C } }
#[derive(Enum, Copy, Clone, Eq, PartialEq)]
#[graphql(remote = "remote_crate::RemoteEnum")]
enum LocalEnum {
Expand Down

0 comments on commit d0f7097

Please sign in to comment.