I have tried almost everything but contextType still does not work as expected. Is there any example?
Inside my types.tx Context is properly imported, but in the resolver, there is a plain object.
Could you provide an example / small reproduction?
I got my implementation working. Important to note that path to your context.ts file should be relative to the "generate" output specified in your codegen.yml.
overwrite: true
schema: 'src/schema.graphql'
documents: null
generates:
src/generated/graphql.ts:
config:
# ensure this path is relative to "src/generated/graphql.ts"
contextType: ../context#MyContext
And then your context file should be of similar format:
// src/context.ts
export interface MyContext {
username: string;
}
@steida can you please provide your codegen.yml file?
@ctrlplusb You can now just specify your type, and use add plugin to do the imports, it makes it easier to use.
overwrite: true
schema: 'src/schema.graphql'
documents: null
generates:
src/generated/graphql.ts:
plugins:
- add: "import { MyContext } from './context';"
- typescript-common
- typescript-server
- typescript-resolvers
config:
# ensure this path is relative to "src/generated/graphql.ts"
contextType: MyContext
@steida, I'm closing for now, feel free to re-open if it's still relevant.
@steida For what it is worth, it will still default to a {} all around unless you name it something other than Context it appears.
That was my problem at least. Here is my codegen.yml. Notice the "MyContext" renaming.:
```
schema: ./src/graphql/index.ts
require:
Alternatively, you can also point to the exact exported type as a value of the config.contextType property, without having to use the add plugin:
generates:
./schema.ts:
config:
contextType: ./Context#MyContext
plugins:
- typescript
- typescript-operations
- typescript-resolvers
Given then there's a Context.ts file relative to the generated schema.ts:
// Context.ts
export interface MyContext {
foo: 'bar'
}
Now in your resolvers you can access a type-safe context:
getResources(root, args, context) {
context.foo // "bar"
}
Most helpful comment
Alternatively, you can also point to the exact exported type as a value of the
config.contextTypeproperty, without having to use theaddplugin:Given then there's a
Context.tsfile relative to the generatedschema.ts:Now in your resolvers you can access a type-safe context: