Skip to content

Commit 13972e2

Browse files
committed
Document derived context
1 parent f9b80ae commit 13972e2

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

website/docs/04-docblock-tags/04-context.mdx

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ type GQLCtx = {
1313
};
1414
```
1515

16+
## Consuming context values in resolvers
17+
1618
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:
1719

1820
```ts
@@ -37,7 +39,40 @@ export function me(ctx: GQLCtx): User {
3739
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.
3840
:::
3941

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+
export function me(ctx: GQLCtx, db: Database): User {
58+
return db.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 = new WeakMap<GQLCtx, Database>();
65+
66+
/** @gqlContext */
67+
function createContext(ctx: GQLCtx): Database {
68+
if (!DB_CACHE.has(ctx)) {
69+
DB_CACHE.set(ctx, new Database());
70+
}
71+
return DB_CACHE.get(ctx);
72+
}
73+
```
74+
75+
## Constructing your root context object
4176

4277
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.
4378

0 commit comments

Comments
 (0)