Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save alexstrat/588efd6fbf87386c9cebdf620a07f62f to your computer and use it in GitHub Desktop.
Save alexstrat/588efd6fbf87386c9cebdf620a07f62f to your computer and use it in GitHub Desktop.
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