如何在 graphql 中为参数添加指令

How to add a directive for arguments in graphql

我尝试向我的模式添加一个指令,以便我可以验证像本例中的 id 这样的参数

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

所以基本想法是添加一个这样的指令,它在模式编译的意义上起作用:

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
        }
    }
}

但是当我尝试使用它时,似乎永远不会在传入查询中找到它,这与 Subject 上的 FIELD_DEFINITION 不同,后者会被访问者击中:

你必须用其他参数调用 visitArgumentDefinition@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
    }

}