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 3 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,92 @@
package io.smallrye.graphql.schema.creator.type;

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.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.ClassType;
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.CustomScalarType.CustomScalarPrimitiveType;
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);

Set<String> interfaces = classInfo.interfaceNames().stream().map(DotName::toString)
.collect(Collectors.toSet());
CustomScalarPrimitiveType customScalarPrimitiveType;
if (interfaces.contains("io.smallrye.graphql.scalar.custom.CustomIntScalar")) {
checkForOneArgConstructor(classInfo, BigInteger.class);
customScalarPrimitiveType = INT_TYPE;
} else if (interfaces.contains("io.smallrye.graphql.scalar.custom.CustomFloatScalar")) {
checkForOneArgConstructor(classInfo, BigDecimal.class);
customScalarPrimitiveType = FLOAT_TYPE;
} else if (interfaces.contains("io.smallrye.graphql.scalar.custom.CustomStringScalar")) {
checkForOneArgConstructor(classInfo, String.class);
customScalarPrimitiveType = STRING_TYPE;
} else {
//TODO error handle in the expected way
throw new RuntimeException("Required to implement a known CustomScalar primitive type. "
jmartisk marked this conversation as resolved.
Show resolved Hide resolved
+ "(CustomStringScalar, CustomFloatScalar, CustomIntScalar)");
}

return new CustomScalarType(
classInfo.name().toString(),
scalarName,
DescriptionHelper.getDescriptionForType(annotations).orElse(null),
customScalarPrimitiveType);

}

private static void checkForOneArgConstructor(final ClassInfo classInfo, Class<?> argType) {
if (classInfo.constructors().stream().noneMatch(methodInfo -> methodInfo.parameters().size() == 1
&& methodInfo.parameterType(0).equals(ClassType.create(argType)))) {
//TODO error handle in the expected way
throw new RuntimeException("Required to implement a one arg constructor with paramtype of "
+ argType.getName());
}
}

@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,52 @@
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;

public final class CustomScalarType extends Reference {

private String description;
private CustomScalarPrimitiveType customScalarPrimitiveType;

public CustomScalarType() {
}

public CustomScalarType(String className, String name, String description,
CustomScalarPrimitiveType customScalarPrimitiveType) {
super(className, name, ReferenceType.SCALAR);
this.description = description;
this.customScalarPrimitiveType = customScalarPrimitiveType;
}

public String getDescription() {
return description;
}

public CustomScalarPrimitiveType getCustomScalarPrimitiveType() {
return customScalarPrimitiveType;
}

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

public void setCustomScalarPrimitiveType(CustomScalarPrimitiveType customScalarPrimitiveType) {
this.customScalarPrimitiveType = customScalarPrimitiveType;
}

@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
28 changes: 28 additions & 0 deletions docs/custom-scalar.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
Creating GraphQL Custom Scalars with SmallRye GraphQL
=======
While by default **MicroProfile GraphQL** specification doesn't provide direct support for creating
custom scalars for GraphQL literal types of String, Int and Float, **SmallRye GraphQL** has implemented
this feature based on user feedback. To implement a **custom scalar** with **SmallRye GraphQL**,
you can annotate your custom scalar class with `@CustomScalar` in addition to following the pattern below:
```java
@CustomScalar("BigDecimalString")
public class BigDecimalString implements CustomStringScalar {
public BigDecimalString(String stringValue) {
...
}
@Override
public String stringValueForSerialization() {
...
}
}
```
In this example, `BigDecimalString` implements the `CustomStringScalar` which is used to identify the
proper (de) serialization for BigDecimalString. `BigDecimalString` also provides a single argument
constructor which takes a String. Finally, `BigDecimalString` implements
`stringValueForSerialization()` which provides the String representation to be used during
serialization.
jmartisk marked this conversation as resolved.
Show resolved Hide resolved

> [NOTE]
> If the user wants to create a literal for GraphQL Int or Float, they would implement either
> CustomIntScalar with the intValueForSerialization method or CustomFloatScalar with the
> floatValueForSerialization method respectively.
22 changes: 22 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,22 @@
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;

/**
* Allows for definition of custom graphql scalars. Types with this annotation should extend one of
* CustomStringScalar, CustomIntScalar, or CustomFloatScalar. Additionally, the Type should provide
* a single argument constructor taking the associated type(String, BigInteger, BigDecimal).
*/
@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();
}
Loading
Loading