You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: website/docs/04-docblock-tags/04-context.mdx
+36-1Lines changed: 36 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -13,6 +13,8 @@ type GQLCtx = {
13
13
};
14
14
```
15
15
16
+
## Consuming context values in resolvers
17
+
16
18
Grats will detect any resolver parameter that is typed using the `@gqlContext` type and ensure that the context object is passed to the resolver in that position:
17
19
18
20
```ts
@@ -37,7 +39,40 @@ export function me(ctx: GQLCtx): User {
37
39
Unlike `graphql-js`, Grats does not require that the context object be passed as a specific positional argument to the resolver. You can place the context object anywhere in the argument list, as long as the type is annotated with the `@gqlContext` type.
38
40
:::
39
41
40
-
## Constructing your context object
42
+
## Derived context values
43
+
44
+
In some cases you may have a context value that is expensive to create, or is only used in some resolvers. In these cases you can define a _derived resolver_. A derived resolver is a function produces a context value. It may optionally read, as arguments, other context values, including other derived context values.
45
+
46
+
Once a derived resolver is defined, the type it returns becomes a new context type. **Any resolver argument typed with this type will receive the value produced by the derived resolver returning that type.**
47
+
48
+
:::tip
49
+
Derived context functions will be called individually by each resolve that wants to aces the derived context value. If you want the result to be reused across multiple resolvers, you should memoize the result.
50
+
:::
51
+
52
+
```ts
53
+
/**
54
+
* A resolver which reads both the global context and a derived context value.
55
+
*
56
+
* @gqlQueryContext*/
57
+
exportfunction me(ctx:GQLCtx, db:Database):User {
58
+
returndb.users.getById(ctx.userID);
59
+
}
60
+
61
+
// A derived context resolver cached using a WeakMap to ensure the value is
62
+
// computed at most once per request.
63
+
64
+
const DB_CACHE =newWeakMap<GQLCtx, Database>();
65
+
66
+
/**@gqlContext*/
67
+
function createContext(ctx:GQLCtx):Database {
68
+
if (!DB_CACHE.has(ctx)) {
69
+
DB_CACHE.set(ctx, newDatabase());
70
+
}
71
+
returnDB_CACHE.get(ctx);
72
+
}
73
+
```
74
+
75
+
## Constructing your root context object
41
76
42
77
The mechanism by which you construct your context object will vary depending upon the GraphQL server library you are using. See your GraphQL server library's documentation for more information.
0 commit comments