graphql.schema.GraphQLDirective Java Examples

The following examples show how to use graphql.schema.GraphQLDirective. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GraphQLDocumentationProvider.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
@Nullable
private String getDirectiveDocumentation(GraphQLSchema schema, GraphQLDirectiveDefinition parent) {
    final GraphQLIdentifier directiveName = parent.getNameIdentifier();
    if (directiveName != null) {
        final GraphQLDirective schemaDirective = schema.getDirective(directiveName.getText());
        if (schemaDirective != null) {
            final StringBuilder result = new StringBuilder().append(DEFINITION_START);
            result.append("@").append(schemaDirective.getName());
            result.append(DEFINITION_END);
            final String description = schemaDirective.getDescription();
            if (description != null) {
                result.append(CONTENT_START);
                result.append(GraphQLDocumentationMarkdownRenderer.getDescriptionAsHTML(description));
                result.append(CONTENT_END);
            }
            return result.toString();
        }
    }
    return null;
}
 
Example #2
Source File: FederationSdlPrinter.java    From federation-jvm with MIT License 6 votes vote down vote up
private Options(boolean includeIntrospectionTypes,
                boolean includeScalars,
                boolean includeExtendedScalars,
                boolean includeSchemaDefinition,
                boolean useAstDefinitions,
                boolean descriptionsAsHashComments,
                Predicate<GraphQLDirective> includeDirective,
                Predicate<GraphQLDirective> includeDirectiveDefinition,
                Predicate<GraphQLNamedType> includeTypeDefinition,
                GraphqlTypeComparatorRegistry comparatorRegistry) {
    this.includeIntrospectionTypes = includeIntrospectionTypes;
    this.includeScalars = includeScalars;
    this.includeExtendedScalars = includeExtendedScalars;
    this.includeSchemaDefinition = includeSchemaDefinition;
    this.includeDirective = includeDirective;
    this.includeDirectiveDefinition = includeDirectiveDefinition;
    this.includeTypeDefinition = includeTypeDefinition;
    this.useAstDefinitions = useAstDefinitions;
    this.descriptionsAsHashComments = descriptionsAsHashComments;
    this.comparatorRegistry = comparatorRegistry;
}
 
Example #3
Source File: FederationSdlPrinter.java    From federation-jvm with MIT License 6 votes vote down vote up
private void printFieldDefinitions(PrintWriter out, Comparator<? super GraphQLSchemaElement> comparator, List<GraphQLFieldDefinition> fieldDefinitions) {
    if (fieldDefinitions.size() == 0) {
        return;
    }

    out.format(" {\n");
    fieldDefinitions
            .stream()
            .sorted(comparator)
            .forEach(fd -> {
                printComments(out, fd, "  ");
                List<GraphQLDirective> fieldDirectives = fd.getDirectives();
                if (fd.isDeprecated()) {
                    fieldDirectives = addDeprecatedDirectiveIfNeeded(fieldDirectives);
                }

                out.format("  %s%s: %s%s\n",
                        fd.getName(), argsString(GraphQLFieldDefinition.class, fd.getArguments()), typeString(fd.getType()),
                        directivesString(GraphQLFieldDefinition.class, fieldDirectives));
            });
    out.format("}");
}
 
Example #4
Source File: FederationSdlPrinter.java    From federation-jvm with MIT License 5 votes vote down vote up
private String directiveDefinition(GraphQLDirective directive) {
    StringBuilder sb = new StringBuilder();

    StringWriter sw = new StringWriter();
    printComments(new PrintWriter(sw), directive, "");

    sb.append(sw.toString());

    sb.append("directive @").append(directive.getName());

    GraphqlTypeComparatorEnvironment environment = GraphqlTypeComparatorEnvironment.newEnvironment()
            .parentType(GraphQLDirective.class)
            .elementType(GraphQLArgument.class)
            .build();
    Comparator<? super GraphQLSchemaElement> comparator = options.comparatorRegistry.getComparator(environment);

    List<GraphQLArgument> args = directive.getArguments();
    args = args
            .stream()
            .sorted(comparator)
            .collect(toList());

    sb.append(argsString(GraphQLDirective.class, args));

    sb.append(" on ");

    String locations = directive.validLocations().stream().map(Enum::name).collect(Collectors.joining(" | "));
    sb.append(locations);

    return sb.toString();
}
 
Example #5
Source File: DirectivesAndTypeWalker.java    From samples with MIT License 5 votes vote down vote up
private static boolean walkInputType(GraphQLInputType inputType, List<GraphQLDirective> directives, BiFunction<GraphQLInputType, GraphQLDirective, Boolean> isSuitable) {
  GraphQLInputType unwrappedInputType = Util.unwrapNonNull(inputType);
  for (GraphQLDirective directive : directives) {
    if (isSuitable.apply(unwrappedInputType, directive)) {
      return true;
    }
  }
  if (unwrappedInputType instanceof GraphQLInputObjectType) {
    GraphQLInputObjectType inputObjType = (GraphQLInputObjectType) unwrappedInputType;
    for (GraphQLInputObjectField inputField : inputObjType.getFieldDefinitions()) {
      inputType = inputField.getType();
      directives = inputField.getDirectives();

      if (walkInputType(inputType, directives, isSuitable)) {
        return true;
      }
    }
  }
  if (unwrappedInputType instanceof GraphQLList) {
    GraphQLInputType innerListType = Util.unwrapOneAndAllNonNull(unwrappedInputType);
    if (innerListType instanceof GraphQLDirectiveContainer) {
      directives = ((GraphQLDirectiveContainer) innerListType).getDirectives();
      if (walkInputType(innerListType, directives, isSuitable)) {
        return true;
      }
    }
  }
  return false;
}
 
Example #6
Source File: RangeDirective.java    From samples with MIT License 5 votes vote down vote up
private List<GraphQLError> apply(GraphQLDirectiveContainer it, DataFetchingEnvironment env, Object value) {
  GraphQLDirective directive = it.getDirective("range");
  double min = (double) directive.getArgument("min").getValue();
  double max = (double) directive.getArgument("max").getValue();

  if (value instanceof Double && ((double) value < min || (double) value > max)) {
    return singletonList(
        GraphqlErrorBuilder.newError(env)
            .message(String.format("Argument value %s is out of range. The range is %s to %s.", value, min, max))
            .build()
    );
  }
  return emptyList();
}
 
Example #7
Source File: ObjectScalarMapper.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Override
public GraphQLScalarType toGraphQLType(String typeName, AnnotatedType javaType, TypeMappingEnvironment env) {
    BuildContext buildContext = env.buildContext;

    GraphQLDirective[] directives = buildContext.directiveBuilder.buildScalarTypeDirectives(javaType, buildContext.directiveBuilderParams()).stream()
            .map(directive -> env.operationMapper.toGraphQLDirective(directive, buildContext))
            .toArray(GraphQLDirective[]::new);
    return ClassUtils.isSuperClass(Map.class, javaType)
            ? Scalars.graphQLMapScalar(typeName, directives)
            : Scalars.graphQLObjectScalar(typeName, directives);
}
 
Example #8
Source File: OperationMapper.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
private List<GraphQLDirective> generateDirectives(BuildContext buildContext) {
    return buildContext.additionalDirectives.stream()
            .map(directiveType -> {
                List<Class<?>> concreteSubTypes = ClassUtils.isAbstract(directiveType)
                        ? buildContext.abstractInputHandler.findConcreteSubTypes(ClassUtils.getRawType(directiveType.getType()), buildContext)
                        : Collections.emptyList();
                return buildContext.directiveBuilder.buildClientDirective(directiveType, buildContext.directiveBuilderParams(concreteSubTypes));
            })
            .map(directive -> toGraphQLDirective(directive, buildContext))
            .collect(Collectors.toList());
}
 
Example #9
Source File: OperationMapper.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
public GraphQLDirective toGraphQLDirective(Directive directive, BuildContext buildContext) {
    GraphQLDirective.Builder builder = GraphQLDirective.newDirective()
            .name(directive.getName())
            .description(directive.getDescription())
            .validLocations(directive.getLocations());
    directive.getArguments().forEach(arg -> builder.argument(toGraphQLArgument(arg, buildContext)));
    return buildContext.transformers.transform(builder.build(), directive, this, buildContext);
}
 
Example #10
Source File: GraphQLSchemaGenerator.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
public GraphQLSchemaGenerator withAdditionalDirectives(GraphQLDirective... additionalDirectives) {
    CodeRegistryBuilder noOp = new NoOpCodeRegistryBuilder();
    Arrays.stream(additionalDirectives)
            .forEach(directive -> {
                if (this.additionalDirectives.put(directive.getName(), directive) != null) {
                    throw new ConfigurationException("Directive name collision: multiple registered additional directives are named '" + directive.getName() + "'");
                }
                directive.getArguments().forEach(arg -> merge(arg.getType(), this.additionalTypes, noOp, this.codeRegistry));
            });
    return this;
}
 
Example #11
Source File: GraphQLSchemaGenerator.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
private boolean isRealType(GraphQLNamedType type) {
    // Reject introspection types
    return !(GraphQLUtils.isIntrospectionType(type)
            // Reject quasi-types
            || type instanceof GraphQLTypeReference
            || type instanceof GraphQLArgument
            || type instanceof GraphQLDirective
            // Reject root types
            || type.getName().equals(messageBundle.interpolate(queryRoot))
            || type.getName().equals(messageBundle.interpolate(mutationRoot))
            || type.getName().equals(messageBundle.interpolate(subscriptionRoot)));
}
 
Example #12
Source File: Directives.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> parseDirective(Directive dir, DataFetchingEnvironment env) {
    GraphQLDirective directive = env.getGraphQLSchema().getDirective(dir.getName());
    if (directive == null) {
        return null;
    }
    return Collections.unmodifiableMap(
            valuesResolver.getArgumentValues(env.getGraphQLSchema().getCodeRegistry(), directive.getArguments(),
                    dir.getArguments(), env.getVariables()));
}
 
Example #13
Source File: Scalars.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
public static GraphQLScalarType graphQLMapScalar(String name, GraphQLDirective[] directives) {
    return GraphQLScalarType.newScalar()
            .name(name)
            .description("Built-in scalar for map-like structures")
            .withDirectives(directives)
            .coercing(MAP_SCALAR_COERCION)
            .build();
}
 
Example #14
Source File: Scalars.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
public static GraphQLScalarType graphQLObjectScalar(String name, GraphQLDirective[] directives) {
    return GraphQLScalarType.newScalar()
            .name(name)
            .description("Built-in scalar for dynamic values")
            .withDirectives(directives)
            .coercing(OBJECT_SCALAR_COERCION)
            .build();
}
 
Example #15
Source File: Directives.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
public static GraphQLDirective mappedType(AnnotatedType type) {
    return GraphQLDirective.newDirective()
            .name(MAPPED_TYPE)
            .description("")
            .validLocation(Introspection.DirectiveLocation.OBJECT)
            .argument(GraphQLArgument.newArgument()
                    .name(TYPE)
                    .description("")
                    .value(type)
                    .type(UNREPRESENTABLE)
                    .build())
            .build();
}
 
Example #16
Source File: Directives.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
public static GraphQLDirective mappedOperation(Operation operation) {
    return GraphQLDirective.newDirective()
            .name(MAPPED_OPERATION)
            .description("")
            .validLocation(Introspection.DirectiveLocation.FIELD_DEFINITION)
            .argument(GraphQLArgument.newArgument()
                    .name(OPERATION)
                    .description("")
                    .value(operation)
                    .type(UNREPRESENTABLE)
                    .build())
            .build();
}
 
Example #17
Source File: Directives.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
public static GraphQLDirective mappedInputField(InputField inputField) {
    return GraphQLDirective.newDirective()
            .name(MAPPED_INPUT_FIELD)
            .description("")
            .validLocation(Introspection.DirectiveLocation.INPUT_FIELD_DEFINITION)
            .argument(GraphQLArgument.newArgument()
                    .name(INPUT_FIELD)
                    .description("")
                    .value(inputField)
                    .type(UNREPRESENTABLE)
                    .build())
            .build();
}
 
Example #18
Source File: FederationSdlPrinter.java    From federation-jvm with MIT License 5 votes vote down vote up
private List<GraphQLDirective> addDeprecatedDirectiveIfNeeded(List<GraphQLDirective> directives) {
    if (!hasDeprecatedDirective(directives)) {
        directives = new ArrayList<>(directives);
        directives.add(DeprecatedDirective4Printing);
    }
    return directives;
}
 
Example #19
Source File: FederationSdlPrinter.java    From federation-jvm with MIT License 5 votes vote down vote up
private TypePrinter<GraphQLEnumType> enumPrinter() {
    return (out, type, visibility) -> {
        if (isIntrospectionType(type)) {
            return;
        }

        GraphqlTypeComparatorEnvironment environment = GraphqlTypeComparatorEnvironment.newEnvironment()
                .parentType(GraphQLEnumType.class)
                .elementType(GraphQLEnumValueDefinition.class)
                .build();
        Comparator<? super GraphQLSchemaElement> comparator = options.comparatorRegistry.getComparator(environment);

        if (shouldPrintAsAst(type.getDefinition())) {
            printAsAst(out, type.getDefinition(), type.getExtensionDefinitions());
        } else {
            printComments(out, type, "");
            out.format("enum %s%s", type.getName(), directivesString(GraphQLEnumType.class, type.getDirectives()));
            List<GraphQLEnumValueDefinition> values = type.getValues()
                    .stream()
                    .sorted(comparator)
                    .collect(toList());
            if (values.size() > 0) {
                out.format(" {\n");
                for (GraphQLEnumValueDefinition enumValueDefinition : values) {
                    printComments(out, enumValueDefinition, "  ");
                    List<GraphQLDirective> enumValueDirectives = enumValueDefinition.getDirectives();
                    if (enumValueDefinition.isDeprecated()) {
                        enumValueDirectives = addDeprecatedDirectiveIfNeeded(enumValueDirectives);
                    }
                    out.format("  %s%s\n", enumValueDefinition.getName(), directivesString(GraphQLEnumValueDefinition.class, enumValueDirectives));
                }
                out.format("}");
            }
            out.format("\n\n");
        }
    };
}
 
Example #20
Source File: FederationSdlPrinter.java    From federation-jvm with MIT License 5 votes vote down vote up
private String directiveDefinitions(List<GraphQLDirective> directives) {
    StringBuilder sb = new StringBuilder();
    for (GraphQLDirective directive : directives) {
        sb.append(directiveDefinition(directive));
        sb.append("\n\n");
    }
    return sb.toString();
}
 
Example #21
Source File: OperationMapper.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
public List<GraphQLDirective> getDirectives() {
    return directives;
}
 
Example #22
Source File: FederationDirectives.java    From federation-jvm with MIT License 4 votes vote down vote up
public static GraphQLDirective requires(String fields) {
    return newDirective(requires)
            .argument(fieldsArgument(fields))
            .build();
}
 
Example #23
Source File: FederationDirectives.java    From federation-jvm with MIT License 4 votes vote down vote up
public static GraphQLDirective provides(String fields) {
    return newDirective(provides)
            .argument(fieldsArgument(fields))
            .build();
}
 
Example #24
Source File: FederationSdlPrinter.java    From federation-jvm with MIT License 4 votes vote down vote up
public Predicate<GraphQLDirective> getIncludeDirective() {
    return includeDirective;
}
 
Example #25
Source File: FederationSdlPrinter.java    From federation-jvm with MIT License 4 votes vote down vote up
public Predicate<GraphQLDirective> getIncludeDirectiveDefinition() {
    return includeDirectiveDefinition;
}
 
Example #26
Source File: FederationSdlPrinter.java    From federation-jvm with MIT License 4 votes vote down vote up
public Options includeDirectives(Predicate<GraphQLDirective> includeDirective) {
    return new Options(this.includeIntrospectionTypes, this.includeScalars, this.includeExtendedScalars, this.includeSchemaDefinition, this.useAstDefinitions, this.descriptionsAsHashComments, includeDirective, this.includeDirectiveDefinition, this.includeTypeDefinition, this.comparatorRegistry);
}
 
Example #27
Source File: FederationSdlPrinter.java    From federation-jvm with MIT License 4 votes vote down vote up
private TypePrinter<GraphQLSchema> schemaPrinter() {
    return (out, schema, visibility) -> {
        GraphQLObjectType queryType = schema.getQueryType();
        GraphQLObjectType mutationType = schema.getMutationType();
        GraphQLObjectType subscriptionType = schema.getSubscriptionType();

        // when serializing a GraphQL schema using the type system language, a
        // schema definition should be omitted if only uses the default root type names.
        boolean needsSchemaPrinted = options.isIncludeSchemaDefinition();

        if (!needsSchemaPrinted) {
            if (queryType != null && !queryType.getName().equals("Query")) {
                needsSchemaPrinted = true;
            }
            if (mutationType != null && !mutationType.getName().equals("Mutation")) {
                needsSchemaPrinted = true;
            }
            if (subscriptionType != null && !subscriptionType.getName().equals("Subscription")) {
                needsSchemaPrinted = true;
            }
        }

        if (needsSchemaPrinted) {
            out.format("schema {\n");
            if (queryType != null) {
                out.format("  query: %s\n", queryType.getName());
            }
            if (mutationType != null) {
                out.format("  mutation: %s\n", mutationType.getName());
            }
            if (subscriptionType != null) {
                out.format("  subscription: %s\n", subscriptionType.getName());
            }
            out.format("}\n\n");
        }

        List<GraphQLDirective> directives = getSchemaDirectives(schema);
        if (!directives.isEmpty()) {
            out.format("%s", directiveDefinitions(directives));
        }
    };
}
 
Example #28
Source File: FederationSdlPrinter.java    From federation-jvm with MIT License 4 votes vote down vote up
private List<GraphQLDirective> getSchemaDirectives(GraphQLSchema schema) {
    return schema.getDirectives().stream()
            .filter(options.getIncludeDirective())
            .filter(options.getIncludeDirectiveDefinition())
            .collect(toList());
}
 
Example #29
Source File: FederationSdlPrinter.java    From federation-jvm with MIT License 4 votes vote down vote up
private String directiveString(GraphQLDirective directive) {
    if (!options.getIncludeDirective().test(directive)) {
        // @deprecated is special - we always print it if something is deprecated
        if (!isDeprecatedDirective(directive)) {
            return "";
        }
    }

    StringBuilder sb = new StringBuilder();
    sb.append("@").append(directive.getName());

    GraphqlTypeComparatorEnvironment environment = GraphqlTypeComparatorEnvironment.newEnvironment()
            .parentType(GraphQLDirective.class)
            .elementType(GraphQLArgument.class)
            .build();
    Comparator<? super GraphQLSchemaElement> comparator = options.comparatorRegistry.getComparator(environment);

    List<GraphQLArgument> args = directive.getArguments();
    args = args
            .stream()
            .sorted(comparator)
            .collect(toList());
    if (!args.isEmpty()) {
        sb.append("(");
        for (int i = 0; i < args.size(); i++) {
            GraphQLArgument arg = args.get(i);
            String argValue = null;
            if (arg.getValue() != null) {
                argValue = printAst(arg.getValue(), arg.getType());
            } else if (arg.getDefaultValue() != null) {
                argValue = printAst(arg.getDefaultValue(), arg.getType());
            }
            if (!isNullOrEmpty(argValue)) {
                sb.append(arg.getName());
                sb.append(" : ");
                sb.append(argValue);
                if (i < args.size() - 1) {
                    sb.append(", ");
                }
            }
        }
        sb.append(")");
    }
    return sb.toString();
}
 
Example #30
Source File: OperationMapper.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
private GraphQLDirective[] toGraphQLDirectives(TypedElement element, BiFunction<AnnotatedElement, DirectiveBuilderParams, List<Directive>> directiveBuilder, BuildContext buildContext) {
    return element.getElements().stream()
            .flatMap(el -> directiveBuilder.apply(el, buildContext.directiveBuilderParams()).stream())
            .map(directive -> toGraphQLDirective(directive, buildContext))
            .toArray(GraphQLDirective[]::new);
}