Skip to content

Support for operation directives #947

@Fryuni

Description

@Fryuni

The discussion on issue #53 seems to be about schema directives, so I'm opening a new issue regarding query directives which is also not supported,

It seems quite simple to add this feature by passing an extra field to the GraphQLSchema constructor here:

nexus/src/builder.ts

Lines 1700 to 1709 in 8e0ce1b

const schema = new GraphQLSchema({
query: Query,
mutation: Mutation,
subscription: Subscription,
types: objValues(typeMap),
extensions: {
...config.extensions,
nexus: schemaExtension,
},
}) as NexusGraphQLSchema

Since that is just one function down from makeSchema and uses the same type, all it requires is adding a new field on the SchemaConfig here and passing it along. I tested it locally, and it works perfectly. The schema gets generated correctly with the directive specification at the top, and the information is passed to the resolvers at info.fieldNodes.directives as graphql-js defines.

Here is how it ended up being with this change:

/* file: directives.ts */
import {GraphQLDirective, GraphQLInt} from 'graphql';

export const cacheDirective = new GraphQLDirective({
    name: 'cached',
    args: {
        lifetime: {
            type: GraphQLInt,
        },
    },
    locations: ['FIELD'],
});

/* file: schema.ts */
import {makeSchema} from 'nexus';
import {cacheDirective} from './directives';

export const NexusGraphQLSchema = makeSchema({
    directives: [cacheDirective],
    ...
});

/* file: testResolver.ts */
import {queryField} from 'nexus';
import {cacheDirective} from '../directives';
import {getArgumentValues} from 'graphql/execution/values';

export const testField = queryField(def => def.string('testField', {
     resolve: (_, __, ___, info) => {
        const cacheConfiguration = getDirectiveValues(cacheDirective, info.fieldNodes[0], info.variableValues);
        return cacheConfiguration?.lifetime?.toFixed(0) ?? 'no-cache';
    },
});

It seems deceptively simple for no one to have done it by now, is there a problem with this that happens not to affect my application, or should I open a PR?

Metadata

Metadata

Assignees

No one assigned

    Labels

    type/featAdd a new capability or enhance an existing one

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions