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
fix: context params and pass req and res in an object (#1295)
`req` and `res` are now also set by default in the GraphQL context.
BREAKING CHANGES:
- The function passed to `schema.addToContext` (known as a "Context Adder") no longer has its first parameter being the request object. Instead it now receives an object (known as the "Context Adder Lens") _containing_ the request object. In addition, on this lens, the response object can also be found. The lens exposes the request and response objects on properties `req` and `res` respectively. If you feel strongly that they should be `request` and `response` or any other thoughts you have please let us know on the issue tracker!
before:
```ts
schema.addToContext((req) => {
// do something
})
```
after:
```ts
schema.addToContext(({ req, res }}) => {
// do something
})
```
Copy file name to clipboardExpand all lines: website/content/040-api/01-nexus/01-schema.mdx
+29-1
Original file line number
Diff line number
Diff line change
@@ -922,12 +922,16 @@ Sugar for creating arguments of type `Int` `String` `Float` `ID` `Boolean`.
922
922
923
923
Add context to your graphql resolver functions. The objects returned by your context contributor callbacks will be shallow-merged into `ctx`. The `ctx` type will also accurately reflect the types you return from callbacks passed to `addToContext`.
924
924
925
+
The incoming request and server response are passed to the callback in the following shape: `{ req: IncomingMessage, res: ServerResponse }`. See below how to use them.
926
+
925
927
### Example
926
928
929
+
Defining arbitrary values to your GraphQL context
930
+
927
931
```ts
928
932
import { schema } from'nexus'
929
933
930
-
schema.addToContext(_req=> {
934
+
schema.addToContext(({ req, res })=> {
931
935
return {
932
936
greeting: 'Howdy!',
933
937
}
@@ -944,6 +948,30 @@ schema.queryType({
944
948
})
945
949
```
946
950
951
+
Forwarding the incoming request to your GraphQL Context
952
+
953
+
```ts
954
+
import { schema } from'nexus'
955
+
956
+
schema.addToContext(({ req, res }) => {
957
+
return {
958
+
req
959
+
}
960
+
})
961
+
962
+
schema.queryType({
963
+
definition(t) {
964
+
t.string('hello', {
965
+
resolve(_root, _args, ctx) {
966
+
if (ctx.req.headers['authorization']) {
967
+
/* ... */
968
+
}
969
+
},
970
+
})
971
+
},
972
+
})
973
+
```
974
+
947
975
## `use`
948
976
949
977
Add schema plugins to your app. These plugins represent a subset of what framework plugins ([`app.use`](../../api/nexus/use) can do. This is useful when, for example, a schema plugin you would like to use has not integrated into any framework plugin. You can find a list of schema plugins [here](../../components-standalone/schema/plugins).
0 commit comments