Add schema directive for all the queries in GraphQL
Asked Answered
C

1

7
  1. Is there a way to add a schema directive by overriding one of the methods of SchemaDirectiveVisitor for all the queries and mutations? For example to check the authentication token in a directive. Would be nice to add it just once not for every query/mutation defined.
  2. If yes, which one of the following methods should be overwritten and how? I wasn't able to find an example on how to override each of them.

    • visitSchema(schema: GraphQLSchema)
    • visitScalar(scalar: GraphQLScalarType)
    • visitObject(object: GraphQLObjectType)
    • visitFieldDefinition(field: GraphQLField<any, any>)
    • visitArgumentDefinition(argument: GraphQLArgument)
    • visitInterface(iface: GraphQLInterfaceType)
    • visitUnion(union: GraphQLUnionType)
    • visitEnum(type: GraphQLEnumType)
    • visitEnumValue(value: GraphQLEnumValue)
    • visitInputObject(object: GraphQLInputObjectType)
    • visitInputFieldDefinition(field: GraphQLInputField)

My intuition would say that visitObject(object: GraphQLObjectType) since type Query is a GraphQLObjectType.

  1. What will be the DirectiveLocation in the end? OBJECT or QUERY/MUTATION?
Camala answered 10/1, 2019 at 6:57 Comment(0)
D
2

To visit objects (you are right Query is) use visitObject and for specific api end (any method in Query) use visitFieldDefinition I have implemented it in following way,

class authDirective extends SchemaDirectiveVisitor {
    visitObject(type) {
        this.ensureFieldsWrapped(type);
        type._requiredAuthRole = this.args.requires;
    }

    visitFieldDefinition(field, details) {
        this.ensureFieldsWrapped(details.objectType);
        field._requiredAuthRole = this.args.requires;
    }
    ensureFieldsWrapped(objectType){
        const fields = objectType.getFields();
        //your logic to resolve directive
    }
}
module.exports = authDirective;

In graphQL shema

directive @authorization(requires: Role) on OBJECT | FIELD_DEFINITION

In schema-builder or server include

resolvers,
schemaDirectives: {
    authorization: authDirective
}
Divinize answered 23/1, 2019 at 18:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.