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

55 lines
1.7 KiB
Markdown
Raw Normal View History

2020-04-15 03:15:30 +00:00
# Cache control
2020-05-09 21:39:04 +00:00
Production environments often rely on caching to improve performance.
A GraphQL query will call multiple resolver functions and each resolver can have a different cache definition. Some may cache for a few seconds, some may cache for a few hours, some may be the same for all users, and some may be different for each session.
2020-09-01 05:47:22 +00:00
`Async-graphql` provides a mechanism that allows you to define the cache time and scope for each resolver.
2020-05-09 21:39:04 +00:00
You can define cache parameters on the object or on its fields. The following example shows two uses of cache control parameters.
You can use `max_age` parameters to control the age of the cache (in seconds), and you can also use `public` and `private` to control the scope of the cache. When you do not specify it, the scope will default to `public`.
2020-09-01 05:47:22 +00:00
when querying multiple resolvers, the results of all cache control parameters will be combined and the `max_age` minimum value will be taken. If the scope of any object or field is `private`, the result will be `private`.
2020-05-09 21:39:04 +00:00
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))]
2020-05-09 21:39:04 +00:00
impl Query {
2020-09-28 09:44:00 +00:00
#[graphql(cache_control(max_age = 30))]
2020-05-09 21:39:04 +00:00
async fn value1(&self) -> i32 {
1
2020-05-09 21:39:04 +00:00
}
2020-09-28 09:44:00 +00:00
#[graphql(cache_control(private))]
2020-05-09 21:39:04 +00:00
async fn value2(&self) -> i32 {
2
2020-05-09 21:39:04 +00:00
}
async fn value3(&self) -> i32 {
3
2020-05-09 21:39:04 +00:00
}
}
```
The following are different queries corresponding to different cache control results:
```graphql
# max_age=30
{ value1 }
```
```graphql
# max_age=30, private
{ value1 value2 }
```
```graphql
# max_age=60
{ value3 }
```