Skip to content

Commit 13fc0da

Browse files
esseswannLegNeato
authored andcommitted
Using newtype for context
1 parent 6ba8ead commit 13fc0da

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

docs/book/content/types/objects/using_contexts.md

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -101,23 +101,29 @@ For example, when using async runtime with [work stealing][2] (like `tokio`), wh
101101
# use juniper::graphql_object;
102102
use tokio::sync::RwLock;
103103

104-
impl juniper::Context for Database {}
105-
106104
struct Database {
107105
requested_count: HashMap<i32, i32>,
108106
}
109107

108+
// Since we cannot directly implement juniper::Context
109+
// for RwLock we use the newtype idiom
110+
struct DatabaseContext(RwLock<Database>)
111+
112+
impl juniper::Context for DatabaseContext {}
113+
110114
struct User {
111115
id: i32,
112116
name: String
113117
}
114118

115-
#[graphql_object(context=RwLock<Database>)]
119+
#[graphql_object(context=DatabaseContext)]
116120
impl User {
117-
async fn times_requested<'db>(&self, context: &'db RwLock<Database>) -> i32 {
121+
async fn times_requested<'db>(&self, context: &'db DatabaseContext) -> i32 {
118122
// Acquire a mutable reference and await if async RwLock is used,
119123
// which is necessary if context consists async operations like
120124
// querying remote databases.
125+
// Obtain base type
126+
let DatabaseContext(context) = context;
121127
// If context is immutable use .read() on RwLock.
122128
let mut context = context.write().await;
123129
// Preform a mutable operation.

0 commit comments

Comments
 (0)