Andreas Köberle
Andreas Köberle

Reputation: 110892

How to add a directive for arguments in graphql

I try to add a directive to my schema so I can validate arguments like the id in this example

type Query {
 subject(id: ID): Subject
}

so the base idea was to add a directive like this, which works in the sense that the schema compiles:

directive @validate on ARGUMENT_DEFINITION | FIELD_DEFINITION

type Subject {
   id: String @validate
}
type Query {
    subject(id: ID! @validate): Subject
}
class InputValidationDirective extends SchemaDirectiveVisitor {
    visitArgumentDefinition(field) {
        const { resolve = defaultFieldResolver } = field

        field.resolve = async function (...args) {
            const result = await resolve.apply(this, args)
            console.log(result) // never happen
            return result
        }
    }

    visitFieldDefinition(field) {
        const { resolve = defaultFieldResolver } = field
        field.resolve = async function (...args) {
            const result = await resolve.apply(this, args)
            console.log(result)
            return result
        }
    }
}

but when I try to use it seems never to be found on a incoming query, unlike the FIELD_DEFINITION on Subject which gets hit by the visitor:

Upvotes: 1

Views: 647

Answers (1)

BernhardS
BernhardS

Reputation: 1088

u have to call visitArgumentDefinition with other arguments, @see here

visitArgumentDefinition(argument, objectType) {

    const { resolve = defaultFieldResolver } = objectType.field
    
    objectType.field.resolve = async (...args) => {

        const result = await resolve.apply(this, args)
        console.log(result) // never happen
        return result
    }

}

Upvotes: 1

Related Questions