4.3.0
New "client context"
You can now pass typed context from your Nuxt app to the GraphQL middleware using a new feature called client options. This is a file you can create (similar to server options) called graphqlMiddleware.clientOptions.ts
. It currently supports a single method called buildClientContext()
. It allows you to define a type and build a context object. When using a composable such as useGraphqlQuery()
this context will be built before performing the request and encoded as a query param. On the server side you then have access to this context inside all server options methods:
graphqlMiddleware.clientOptions.ts
import { defineGraphqlClientOptions } from 'nuxt-graphql-middleware/dist/runtime/clientOptions'
export default defineGraphqlClientOptions<{
country: 'US' | 'DE' | 'FR'
}>({
buildClientContext() {
const country = useCurrentCountry()
return {
country: country.value,
}
},
})
graphqlMiddleware.serverOptions.ts
import { defineGraphqlServerOptions } from 'nuxt-graphql-middleware/dist/runtime/serverOptions'
export default defineGraphqlServerOptions({
serverFetchOptions: function (event, _operation, operationName, context) {
// Pass the current country as a header when making a request to the
// GraphQL server.
return {
headers: {
'x-current-country': context.client?.country || 'US',
},
}
},
})
Server utils
Both useGraphqlQuery
and useGraphqlMutation
were previously available via import from a special alias inside a nitro context (such as event handlers):
import { useGraphqlQuery } from '#graphql-composable'
export default defineEventHandler(async () => {
const data = await useGraphqlQuery('users')
return data.data.users.map((v) => v.email)
})
Unfortunately this has lead to some issues with a recent Nuxt update; most notably the method's arguments and return value were completely untyped. Because of that these two methods are now available as server utils and are automatically imported. You will have to remove all existing imports:
export default defineEventHandler(async () => {
const data = await useGraphqlQuery('users')
return data.data.users.map((v) => v.email)
})
These server utils also support the new "client context" feature, but the context you define in graphqlMiddleware.clientOptions.ts
is not used here. You can however pass the object directly when using the utils:
const data = await useGraphqlQuery({
name: 'testClientOptions',
clientContext: {
country: 'US',
},
})
What's Changed
- Don't log patterns to the console by @lewebsimple in #42
- fix(docs): correct typo in file upload setting name by @asonnleitner in #44
New Contributors
- @lewebsimple made their first contribution in #42
Full Changelog: release/4.2.0...release/4.3.0