Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add schema directive for all the queries in GraphQL

  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?
like image 285
cosmarc Avatar asked Jan 10 '19 06:01

cosmarc


People also ask

How do I get all schema in GraphQL?

How To Get The Schema — Introspection Queries. Some GraphQL servers don't provide a convenient GraphQL API explorer. Instead, to get the schema we need to send a HTTP request to the GraphQL server endpoint asking for the GraphQL schema. This type of HTTP request is called a GraphQL introspection query.

How do you use directives in GraphQL?

Configure GraphQL types, fields, and argumentsA directive decorates part of a GraphQL schema or operation with additional configuration. Tools like Apollo Server (and Apollo Client) can read a GraphQL document's directives and perform custom logic as appropriate. oldField: String @deprecated(reason: "Use `newField`.")


1 Answers

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
}
like image 164
Amit Bhoyar Avatar answered Sep 28 '22 02:09

Amit Bhoyar