Created
April 29, 2020 18:47
-
-
Save alexstrat/588efd6fbf87386c9cebdf620a07f62f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { GraphQLField, DirectiveNode, TypeNode, isNonNullType } from "graphql"; | |
type FieldVisitorFn = ( | |
field: GraphQLField<any, any>, | |
argumentDirectives: { | |
directiveNode: DirectiveNode, | |
targetNode: TypeNode, | |
path: string | |
}[] | |
) => GraphQLField<any, any> | void | null; | |
function visitFieldDefinitionWithDirectivedArguments( | |
schema, | |
directiveNames: string[], | |
visitor: FieldVisitorFn | |
): void {}; | |
// usage | |
visitFieldDefinitionWithDirectivedArguments( | |
schema, | |
['isMax'], | |
(field, argumentDirectives) => { | |
field.resolve = (parent, variables, context, info) => { | |
for (let { directiveNode, targetNode, path } of argumentDirectives) { | |
const { max } = getArgumentValue(directiveNode); | |
const value = getValue(variables, path); | |
if (value > max) { | |
if (isNonNullType(targetNode)) { | |
throw new ApolloError(`Argument ${path} is not valid: it exceeds ${max}`); | |
} | |
} else { | |
// silently repalced by null | |
setValue(variables, path, null) | |
} | |
} | |
return field.resolve(parent, variables, context, info); | |
} | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment