async-graphql/docs/en/src/context.md

135 lines
3.8 KiB
Markdown
Raw Normal View History

2020-04-15 03:15:30 +00:00
# Context
The main goal of `Context` is to acquire global data attached to Schema and also data related to the actual query being processed.
## Store Data
2021-11-23 20:48:51 +00:00
Inside the `Context` you can put global data, like environment variables, db connection pool, whatever you may need in every query.
The data must implement `Send` and `Sync`.
You can request the data inside a query by just calling `ctx.data::<TypeOfYourData>()`.
**Note that if the return value of resolver function is borrowed from `Context`, you will need to explicitly state the lifetime of the argument.**
The following example shows how to borrow data in `Context`.
```rust
use async_graphql::*;
struct Query;
#[Object]
impl Query {
async fn borrow_from_context_data<'ctx>(
&self,
2021-03-04 04:13:08 +00:00
ctx: &Context<'ctx>
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 19:06:44 +00:00
) -> Result<&'ctx String> {
ctx.data::<String>()
}
}
2020-06-01 11:01:04 +00:00
```
### 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.
An instance of how it would be written inside an application:
```rust
let schema = Schema::build(Query::default(), Mutation::default(), EmptySubscription)
.data(env_struct)
.data(s3_storage)
.data(db_core)
.finish();
```
### Request data
You can put data inside the context at the execution of the request, it's useful for authentication data for instance.
A little example with a `warp` route:
```rust
let graphql_post = warp::post()
.and(warp::path("graphql"))
.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?;
let response = schema
.execute(
request
.data(your_auth_data)
.data(something_else)
).await;
Ok(async_graphql_warp::Response::from(response))
});
```
## Headers
With the Context you can also insert and appends headers.
```rust
#[Object]
impl Query {
async fn greet(&self, ctx: &Context<'_>) -> String {
// Headers can be inserted using the `http` constants
let was_in_headers = ctx.insert_http_header(ACCESS_CONTROL_ALLOW_ORIGIN, "*");
// They can also be inserted using &str
let was_in_headers = ctx.insert_http_header("Custom-Header", "1234");
// If multiple headers with the same key are `inserted` then the most recent
// one overwrites the previous. If you want multiple headers for the same key, use
// `append_http_header` for subsequent headers
let was_in_headers = ctx.append_http_header("Custom-Header", "Hello World");
String::from("Hello world")
}
}
```
## Selection / LookAhead
2021-11-19 00:29:45 +00:00
Sometimes you want to know what fields are requested in the subquery to optimize the processing of data. You can read fields accross the query with `ctx.field()` which will give you a `SelectionField` which will allow you to navigate accross the fields and subfields.
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
use async_graphql::*;
#[derive(SimpleObject)]
struct Detail {
c: i32,
d: i32,
}
#[derive(SimpleObject)]
struct MyObj {
a: i32,
b: i32,
detail: Detail,
}
struct Query;
#[Object]
impl Query {
async fn obj(&self, ctx: &Context<'_>) -> MyObj {
if ctx.look_ahead().field("a").exists() {
// This is a query like `obj { a }`
} else if ctx.look_ahead().field("detail").field("c").exists() {
// This is a query like `obj { detail { c } }`
} else {
// This query doesn't have `a`
}
unimplemented!()
}
}
```