Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP Custom Scalar Proof of Concept #1988

Merged
merged 6 commits into from
Dec 22, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -586,6 +586,7 @@ private static Map<DotName, AnnotationInstance> getAnnotationsWithFilter(org.jbo

// SmallRye GraphQL Annotations (Experimental)
public static final DotName TO_SCALAR = DotName.createSimple("io.smallrye.graphql.api.ToScalar"); // TODO: Remove
public static final DotName CUSTOM_SCALAR = DotName.createSimple("io.smallrye.graphql.api.CustomScalar");
public static final DotName ADAPT_TO_SCALAR = DotName.createSimple("io.smallrye.graphql.api.AdaptToScalar");
public static final DotName ADAPT_WITH = DotName.createSimple("io.smallrye.graphql.api.AdaptWith");
public static final DotName ERROR_CODE = DotName.createSimple("io.smallrye.graphql.api.ErrorCode");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package io.smallrye.graphql.schema;

import static io.smallrye.graphql.schema.Annotations.CUSTOM_SCALAR;
import static io.smallrye.graphql.schema.Annotations.DIRECTIVE;

import java.util.ArrayList;
Expand Down Expand Up @@ -28,6 +29,7 @@
import io.smallrye.graphql.schema.creator.OperationCreator;
import io.smallrye.graphql.schema.creator.ReferenceCreator;
import io.smallrye.graphql.schema.creator.type.Creator;
import io.smallrye.graphql.schema.creator.type.CustomScalarCreator;
import io.smallrye.graphql.schema.creator.type.EnumCreator;
import io.smallrye.graphql.schema.creator.type.InputTypeCreator;
import io.smallrye.graphql.schema.creator.type.InterfaceCreator;
Expand Down Expand Up @@ -73,6 +75,7 @@ public class SchemaBuilder {
private final OperationCreator operationCreator;
private final DirectiveTypeCreator directiveTypeCreator;
private final UnionCreator unionCreator;
private final CustomScalarCreator customScalarCreator;

private final DotName FEDERATION_ANNOTATIONS_PACKAGE = DotName.createSimple("io.smallrye.graphql.api.federation");

Expand Down Expand Up @@ -109,6 +112,7 @@ private SchemaBuilder(TypeAutoNameStrategy autoNameStrategy) {
interfaceCreator = new InterfaceCreator(referenceCreator, fieldCreator, operationCreator);
directiveTypeCreator = new DirectiveTypeCreator(referenceCreator);
unionCreator = new UnionCreator(referenceCreator);
customScalarCreator = new CustomScalarCreator(referenceCreator);
}

private Schema generateSchema() {
Expand All @@ -127,6 +131,8 @@ private Schema generateSchema() {
// add AppliedSchemaDirectives and Schema Description
setUpSchemaDirectivesAndDescription(schema, graphQLApiAnnotations, directivesHelper);

addCustomScalarTypes(schema);

for (AnnotationInstance graphQLApiAnnotation : graphQLApiAnnotations) {
ClassInfo apiClass = graphQLApiAnnotation.target().asClass();
List<MethodInfo> methods = getAllMethodsIncludingFromSuperClasses(apiClass);
Expand Down Expand Up @@ -187,7 +193,18 @@ private void addDirectiveTypes(Schema schema) {
schema.addDirectiveType(RolesAllowedDirectivesHelper.ROLES_ALLOWED_DIRECTIVE_TYPE);
}

private void addCustomScalarTypes(Schema schema) {
Collection<AnnotationInstance> annotations = ScanningContext.getIndex().getAnnotations(CUSTOM_SCALAR);

for (AnnotationInstance annotationInstance : annotations) {
schema.addCustomScalarType(customScalarCreator.create(
annotationInstance.target().asClass(),
annotationInstance.value().asString()));
}
}

private void setupDirectives(Directives directives) {
customScalarCreator.setDirectives(directives);
inputTypeCreator.setDirectives(directives);
typeCreator.setDirectives(directives);
interfaceCreator.setDirectives(directives);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package io.smallrye.graphql.schema.creator.type;

import java.util.List;
import java.util.stream.Collectors;

import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.logging.Logger;

import io.smallrye.graphql.schema.Annotations;
import io.smallrye.graphql.schema.creator.ModelCreator;
import io.smallrye.graphql.schema.creator.ReferenceCreator;
import io.smallrye.graphql.schema.helper.DescriptionHelper;
import io.smallrye.graphql.schema.helper.Directives;
import io.smallrye.graphql.schema.model.CustomScalarType;
import io.smallrye.graphql.schema.model.DirectiveInstance;

public class CustomScalarCreator extends ModelCreator {

private static final Logger LOG = Logger.getLogger(CustomScalarCreator.class.getName());

private Directives directives;

public CustomScalarCreator(ReferenceCreator referenceCreator) {
super(referenceCreator);
}

public CustomScalarType create(
ClassInfo classInfo,
String scalarName) {
LOG.debug("Creating custom scalar from " + classInfo.name().toString());

Annotations annotations = Annotations.getAnnotationsForClass(classInfo);

return new CustomScalarType(
classInfo.name().toString(),
scalarName,
DescriptionHelper.getDescriptionForType(annotations).orElse(null),
classInfo.interfaceNames().stream().map(DotName::toString).collect(Collectors.toSet()));

}

@Override
public String getDirectiveLocation() {
return "SCALAR";
}

private List<DirectiveInstance> getDirectiveInstances(Annotations annotations,
String referenceName) {
return directives.buildDirectiveInstances(annotations, getDirectiveLocation(), referenceName);
}

public void setDirectives(Directives directives) {
this.directives = directives;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package io.smallrye.graphql.schema.model;

import static io.smallrye.graphql.schema.model.CustomScalarType.CustomScalarPrimitiveType.FLOAT_TYPE;
import static io.smallrye.graphql.schema.model.CustomScalarType.CustomScalarPrimitiveType.INT_TYPE;
import static io.smallrye.graphql.schema.model.CustomScalarType.CustomScalarPrimitiveType.STRING_TYPE;

import java.util.Set;

public final class CustomScalarType extends Reference {

private String description;
private CustomScalarPrimitiveType customScalarPrimitiveType;

public CustomScalarType() {
}

public CustomScalarType(String className, String name, String description, Set<String> interfaces) {
super(className, name, ReferenceType.SCALAR);
this.description = description;
if (interfaces.contains("io.smallrye.graphql.scalar.custom.CustomIntScalar")) {
customScalarPrimitiveType = INT_TYPE;
} else if (interfaces.contains("io.smallrye.graphql.scalar.custom.CustomFloatScalar")) {
customScalarPrimitiveType = FLOAT_TYPE;
} else if (interfaces.contains("io.smallrye.graphql.scalar.custom.CustomStringScalar")) {
customScalarPrimitiveType = STRING_TYPE;
} else {
//TODO error handle in the expected way
throw new RuntimeException("Required to implement a known CustomScalar primitive type. "
+ "(CustomStringScalar, CustomFloatScalar, CustomIntScalar");
}
}

public String getDescription() {
return description;
}

public CustomScalarPrimitiveType customScalarPrimitiveType() {
return customScalarPrimitiveType;
}

public void setDescription(String description) {
this.description = description;
}

@Override
public String toString() {
return "CustomScalarType{" +
"name='" + getName() + '\'' +
", description='" + description + '\'' +
", customScalar='" + customScalarPrimitiveType.name() + '\'' +
'}';
}

public enum CustomScalarPrimitiveType {
STRING_TYPE,
INT_TYPE,
FLOAT_TYPE
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,12 @@ public static Reference getIDScalar(String className) {
.build();
}

public static void registerCustomScalarInSchema(
String graphQlScalarName,
String valueClassName) {
populateScalar(valueClassName, graphQlScalarName, valueClassName);
}

// this is for the UUID from graphql-java-extended-scalars
// if used, it will override the original UUID type that is mapped to a String in the schema
public static void addUuid() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public final class Schema implements Serializable {
private Map<Group, Set<Operation>> groupedMutations = new HashMap<>();
private Map<Group, Set<Operation>> groupedSubscriptions = new HashMap<>();

private List<CustomScalarType> customScalarTypes = new ArrayList<>();
private List<DirectiveType> directiveTypes = new ArrayList<>();
private Map<String, InputType> inputs = new HashMap<>();
private Map<String, Type> types = new HashMap<>();
Expand Down Expand Up @@ -320,6 +321,21 @@ private void addToOperationMap(Map<Group, Set<Operation>> map, Group group, Oper
map.put(group, set);
}

public void addCustomScalarType(CustomScalarType customScalarType) {
customScalarTypes.add(customScalarType);
Scalars.registerCustomScalarInSchema(
customScalarType.getName(),
customScalarType.getClassName());
}

public List<CustomScalarType> getCustomScalarTypes() {
return customScalarTypes;
}

public boolean hasCustomScalarTypes() {
return !customScalarTypes.isEmpty();
}

public List<DirectiveType> getDirectiveTypes() {
return directiveTypes;
}
Expand Down Expand Up @@ -347,6 +363,7 @@ public String toString() {
", groupedMutations=" + groupedMutations +
", groupedSubscriptions=" + groupedSubscriptions +
", directiveTypes=" + directiveTypes +
", customScalarTypes=" + customScalarTypes +
", inputs=" + inputs +
", types=" + types +
", interfaces=" + interfaces +
Expand Down
17 changes: 17 additions & 0 deletions server/api/src/main/java/io/smallrye/graphql/api/CustomScalar.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package io.smallrye.graphql.api;

import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import io.smallrye.common.annotation.Experimental;

@Retention(RUNTIME)
@Target(TYPE)
@Experimental("Mark a type as a custom scalar with the given name in the GraphQL schema.")
public @interface CustomScalar {

String value();
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import com.apollographql.federation.graphqljava.Federation;

import graphql.introspection.Introspection.DirectiveLocation;
import graphql.schema.Coercing;
import graphql.schema.DataFetcher;
import graphql.schema.FieldCoordinates;
import graphql.schema.GraphQLArgument;
Expand Down Expand Up @@ -67,7 +68,12 @@
import io.smallrye.graphql.json.JsonBCreator;
import io.smallrye.graphql.json.JsonInputRegistry;
import io.smallrye.graphql.scalar.GraphQLScalarTypes;
import io.smallrye.graphql.scalar.custom.FloatCoercing;
import io.smallrye.graphql.scalar.custom.IntCoercing;
import io.smallrye.graphql.scalar.custom.StringCoercing;
import io.smallrye.graphql.schema.model.Argument;
import io.smallrye.graphql.schema.model.CustomScalarType;
import io.smallrye.graphql.schema.model.CustomScalarType.CustomScalarPrimitiveType;
import io.smallrye.graphql.schema.model.DirectiveArgument;
import io.smallrye.graphql.schema.model.DirectiveInstance;
import io.smallrye.graphql.schema.model.DirectiveType;
Expand Down Expand Up @@ -160,6 +166,8 @@ private void verifyInjectionIsAvailable() {
private void generateGraphQLSchema() {
GraphQLSchema.Builder schemaBuilder = GraphQLSchema.newSchema();

createGraphQLDirectiveTypes();
createGraphQLCustomScalarTypes();
createGraphQLEnumTypes();
createGraphQLDirectiveTypes();

Expand Down Expand Up @@ -223,6 +231,49 @@ private TypeResolver fetchEntityType() {
};
}

private void createGraphQLCustomScalarTypes() {
if (schema.hasCustomScalarTypes()) {
for (CustomScalarType customScalarType : schema.getCustomScalarTypes()) {
createGraphQLCustomScalarType(customScalarType);
}
}
}

private void createGraphQLCustomScalarType(CustomScalarType customScalarType) {
String scalarName = customScalarType.getName();

Coercing<?, ?> coercing = getCoercing(customScalarType);

GraphQLScalarType graphQLScalarType = GraphQLScalarType.newScalar()
.name(scalarName)
.description("Scalar for " + scalarName)
.coercing(coercing)
.build();

GraphQLScalarTypes.registerCustomScalar(
scalarName,
customScalarType.getClassName(),
graphQLScalarType);
}

private static Coercing<?, ?> getCoercing(CustomScalarType customScalarType) {
CustomScalarPrimitiveType primitiveType = customScalarType.customScalarPrimitiveType();

Coercing<?, ?> coercing = null;
switch (primitiveType) {
case STRING_TYPE:
coercing = new StringCoercing(customScalarType.getClassName());
break;
case INT_TYPE:
coercing = new IntCoercing(customScalarType.getClassName());
break;
case FLOAT_TYPE:
coercing = new FloatCoercing(customScalarType.getClassName());
break;
}
return coercing;
}

private void createGraphQLDirectiveTypes() {
if (schema.hasDirectiveTypes()) {
for (DirectiveType directiveType : schema.getDirectiveTypes()) {
Expand Down Expand Up @@ -526,7 +577,7 @@ private GraphQLInputObjectType createGraphQLInputObjectType(InputType inputType)
if (inputType.hasFields()) {
inputObjectTypeBuilder = inputObjectTypeBuilder
.fields(createGraphQLInputObjectFieldsFromFields(inputType.getFields().values()));
// Register this input for posible JsonB usage
// Register this input for possible JsonB usage
JsonInputRegistry.register(inputType);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
import jakarta.json.bind.JsonbBuilder;
import jakarta.json.bind.JsonbConfig;

import io.smallrye.graphql.scalar.custom.CustomFloatScalar;
import io.smallrye.graphql.scalar.custom.CustomIntScalar;
import io.smallrye.graphql.scalar.custom.CustomStringScalar;
import io.smallrye.graphql.schema.model.Field;
import io.smallrye.graphql.schema.model.InputType;

Expand All @@ -21,7 +24,11 @@
public class JsonBCreator {
private static final Jsonb JSONB = JsonbBuilder.create(new JsonbConfig()
.withFormatting(true)
.withNullValues(true)); //null values are required by @JsonbCreator
.withNullValues(true) //null values are required by @JsonbCreator
.withSerializers(CustomStringScalar.SERIALIZER, CustomIntScalar.SERIALIZER,
CustomFloatScalar.SERIALIZER)
.withDeserializers(CustomStringScalar.DESERIALIZER, CustomIntScalar.DESERIALIZER,
CustomFloatScalar.DESERIALIZER));

private static final Map<String, Jsonb> jsonMap = new HashMap<>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,14 @@ public static void addUuid() {
SCALARS_BY_NAME.put(ExtendedScalars.UUID.getName(), ExtendedScalars.UUID);
}

public static void registerCustomScalar(
String graphQlScalarName,
String valueClassName,
GraphQLScalarType graphQLScalarType) {
SCALAR_MAP.put(valueClassName, graphQLScalarType);
SCALARS_BY_NAME.put(graphQlScalarName, graphQLScalarType);
}

// Scalar map we can just create now.
private static final Map<String, GraphQLScalarType> SCALAR_MAP = new HashMap<>();

Expand Down
Loading
Loading