Using newtype for context
This commit is contained in:
parent
6ba8ead1fd
commit
13fc0dadeb
1 changed files with 10 additions and 4 deletions
|
@ -101,23 +101,29 @@ For example, when using async runtime with [work stealing][2] (like `tokio`), wh
|
||||||
# use juniper::graphql_object;
|
# use juniper::graphql_object;
|
||||||
use tokio::sync::RwLock;
|
use tokio::sync::RwLock;
|
||||||
|
|
||||||
impl juniper::Context for Database {}
|
|
||||||
|
|
||||||
struct Database {
|
struct Database {
|
||||||
requested_count: HashMap<i32, i32>,
|
requested_count: HashMap<i32, i32>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Since we cannot directly implement juniper::Context
|
||||||
|
// for RwLock we use the newtype idiom
|
||||||
|
struct DatabaseContext(RwLock<Database>)
|
||||||
|
|
||||||
|
impl juniper::Context for DatabaseContext {}
|
||||||
|
|
||||||
struct User {
|
struct User {
|
||||||
id: i32,
|
id: i32,
|
||||||
name: String
|
name: String
|
||||||
}
|
}
|
||||||
|
|
||||||
#[graphql_object(context=RwLock<Database>)]
|
#[graphql_object(context=DatabaseContext)]
|
||||||
impl User {
|
impl User {
|
||||||
async fn times_requested<'db>(&self, context: &'db RwLock<Database>) -> i32 {
|
async fn times_requested<'db>(&self, context: &'db DatabaseContext) -> i32 {
|
||||||
// Acquire a mutable reference and await if async RwLock is used,
|
// Acquire a mutable reference and await if async RwLock is used,
|
||||||
// which is necessary if context consists async operations like
|
// which is necessary if context consists async operations like
|
||||||
// querying remote databases.
|
// querying remote databases.
|
||||||
|
// Obtain base type
|
||||||
|
let DatabaseContext(context) = context;
|
||||||
// If context is immutable use .read() on RwLock.
|
// If context is immutable use .read() on RwLock.
|
||||||
let mut context = context.write().await;
|
let mut context = context.write().await;
|
||||||
// Preform a mutable operation.
|
// Preform a mutable operation.
|
||||||
|
|
Loading…
Add table
Reference in a new issue