After spending several days rewriting my GraphQL server to Typescript, I found myself struggling with defining Schema Directives. Despite extensive googling, I could not find any examples of using "more advanced" Apollo GraphQL with Typescript.
Everything was working perfectly for me when using plain Javascript. Here is an example of how my Directive looks:
// TS but no difference from JS in terms of extended class or method overriden
export default class UserAuthDirective extends SchemaDirectiveVisitor {
visitFieldDefinition(field: any, details: any) {
field._requiredRole = this.args.role
const { resolve = defaultFieldResolver } = field
field.resolve = function (...args: any) {
// LOGIC CHECKING ROLES
}
}
}
I utilize makeExecutableSchema from the graphql-tools library, which is set up like this:
// Again basically identical with original JS
const schema = makeExecutableSchema({
typeDefs: mergeTypes(types, { all: true }),
resolvers: loadResolvers(),
logger: {
log: (e) => logger.error(e.message, e),
},
allowUndefinedInResolve: false,
inheritResolversFromInterfaces: true,
resolverValidationOptions: {
allowResolversNotInSchema: false,
requireResolversForResolveType: true,
},
schemaDirectives: {
userHas: UserAuthDirective,
// ^^^ Here I'm getting. "Type 'typeof UserAuthDirective' is not assignable to type 'typeof SchemaDirectiveVisitor'. Types of property 'visitSchemaDirectives' are incompatible."
},
})
Due to the constructor of SchemaDirectiveVisitor being protected, I am unable to instantiate the class from there. I am relatively new to Typescript and may be misunderstanding something or missing basic concepts, so any tips or suggestions would be greatly appreciated as I am currently stuck on this issue.
Thank you :-)