You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sling.apache.org by bd...@apache.org on 2020/06/26 12:38:01 UTC
[sling-org-apache-sling-graphql-core] branch feature/SLING-9550
created (now d27f4bb)
This is an automated email from the ASF dual-hosted git repository.
bdelacretaz pushed a change to branch feature/SLING-9550
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-graphql-core.git.
at d27f4bb SLING-9550 - initial scalars support, with hardcoded test scalars for now
This branch includes the following new commits:
new d27f4bb SLING-9550 - initial scalars support, with hardcoded test scalars for now
The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
[sling-org-apache-sling-graphql-core] 01/01: SLING-9550 - initial
scalars support, with hardcoded test scalars for now
Posted by bd...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
bdelacretaz pushed a commit to branch feature/SLING-9550
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-graphql-core.git
commit d27f4bb7b7a33fd2632cb8eac61f2f3b1b7e67c0
Author: Bertrand Delacretaz <bd...@apache.org>
AuthorDate: Fri Jun 26 14:35:26 2020 +0200
SLING-9550 - initial scalars support, with hardcoded test scalars for now
---
.../graphql/core/engine/GraphQLResourceQuery.java | 16 ++-
.../graphql/core/scalars/SlingScalarsProvider.java | 125 +++++++++++++++++++++
.../core/scripting/GraphQLScriptEngine.java | 2 +-
.../core/scripting/GraphQLScriptEngineFactory.java | 8 ++
.../sling/graphql/core/servlet/GraphQLServlet.java | 6 +-
.../graphql/core/engine/CustomScalarsTest.java | 32 +++++-
.../core/engine/GraphQLResourceQueryTest.java | 18 ++-
.../graphql/core/engine/ResourceQueryTestBase.java | 22 ++--
.../AddressDataFetcher.java} | 35 +++---
.../core/schema/SchemaDescriptionsTest.java | 6 +-
src/test/resources/scalars-schema.txt | 35 ++++++
11 files changed, 267 insertions(+), 38 deletions(-)
diff --git a/src/main/java/org/apache/sling/graphql/core/engine/GraphQLResourceQuery.java b/src/main/java/org/apache/sling/graphql/core/engine/GraphQLResourceQuery.java
index 1c10706..9bdc733 100644
--- a/src/main/java/org/apache/sling/graphql/core/engine/GraphQLResourceQuery.java
+++ b/src/main/java/org/apache/sling/graphql/core/engine/GraphQLResourceQuery.java
@@ -31,6 +31,7 @@ import graphql.language.StringValue;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.graphql.api.SchemaProvider;
import org.apache.sling.graphql.api.SlingDataFetcher;
+import org.apache.sling.graphql.core.scalars.SlingScalarsProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -42,6 +43,7 @@ import graphql.schema.idl.RuntimeWiring;
import graphql.schema.idl.SchemaGenerator;
import graphql.schema.idl.SchemaParser;
import graphql.schema.idl.TypeDefinitionRegistry;
+import graphql.schema.GraphQLScalarType;
import java.io.IOException;
import java.util.Collections;
@@ -60,7 +62,9 @@ public class GraphQLResourceQuery {
private final Logger log = LoggerFactory.getLogger(getClass());
- public ExecutionResult executeQuery(SchemaProvider schemaProvider, SlingDataFetcherSelector fetchersSelector,
+ public ExecutionResult executeQuery(SchemaProvider schemaProvider,
+ SlingDataFetcherSelector fetchersSelector,
+ SlingScalarsProvider scalarsProvider,
Resource r,
String [] requestSelectors,
String query, Map<String, Object> variables) throws ScriptException {
@@ -91,7 +95,7 @@ public class GraphQLResourceQuery {
}
log.debug("Resource {} maps to GQL schema {}", r.getPath(), schemaDef);
try {
- final GraphQLSchema schema = buildSchema(schemaDef, fetchersSelector, r);
+ final GraphQLSchema schema = buildSchema(schemaDef, fetchersSelector, scalarsProvider, r);
final GraphQL graphQL = GraphQL.newGraphQL(schema).build();
log.debug("Executing query\n[{}]\nat [{}] with variables [{}]", query, r.getPath(), variables);
ExecutionInput ei = ExecutionInput.newExecutionInput()
@@ -110,14 +114,15 @@ public class GraphQLResourceQuery {
}
}
- private GraphQLSchema buildSchema(String sdl, SlingDataFetcherSelector fetchers, Resource currentResource) throws IOException {
+ private GraphQLSchema buildSchema(String sdl, SlingDataFetcherSelector fetchers, SlingScalarsProvider scalarsProvider, Resource currentResource) throws IOException {
TypeDefinitionRegistry typeRegistry = new SchemaParser().parse(sdl);
- RuntimeWiring runtimeWiring = buildWiring(typeRegistry, fetchers, currentResource);
+ Iterable<GraphQLScalarType> scalars = scalarsProvider.getScalars(typeRegistry.scalars());
+ RuntimeWiring runtimeWiring = buildWiring(typeRegistry, fetchers, scalars, currentResource);
SchemaGenerator schemaGenerator = new SchemaGenerator();
return schemaGenerator.makeExecutableSchema(typeRegistry, runtimeWiring);
}
- private RuntimeWiring buildWiring(TypeDefinitionRegistry typeRegistry, SlingDataFetcherSelector fetchers, Resource r)
+ private RuntimeWiring buildWiring(TypeDefinitionRegistry typeRegistry, SlingDataFetcherSelector fetchers, Iterable<GraphQLScalarType> scalars, Resource r)
throws IOException {
List<ObjectTypeDefinition> types = typeRegistry.getTypes(ObjectTypeDefinition.class);
RuntimeWiring.Builder builder = RuntimeWiring.newRuntimeWiring();
@@ -137,6 +142,7 @@ public class GraphQLResourceQuery {
return typeWiring;
});
}
+ scalars.forEach(builder::scalar);
return builder.build();
}
diff --git a/src/main/java/org/apache/sling/graphql/core/scalars/SlingScalarsProvider.java b/src/main/java/org/apache/sling/graphql/core/scalars/SlingScalarsProvider.java
new file mode 100644
index 0000000..4fa3ac7
--- /dev/null
+++ b/src/main/java/org/apache/sling/graphql/core/scalars/SlingScalarsProvider.java
@@ -0,0 +1,125 @@
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.sling.graphql.core.scalars;
+
+import java.net.URL;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import org.osgi.framework.Constants;
+import org.osgi.service.component.annotations.Component;
+
+import graphql.language.ScalarTypeDefinition;
+import graphql.language.StringValue;
+import graphql.schema.Coercing;
+import graphql.schema.CoercingParseLiteralException;
+import graphql.schema.CoercingParseValueException;
+import graphql.schema.CoercingSerializeException;
+import graphql.schema.GraphQLScalarType;
+
+/**
+ * Provides GraphQL Scalars (leaf data types) for query execution
+ */
+@Component(service = SlingScalarsProvider.class, property = {
+ Constants.SERVICE_DESCRIPTION + "=Apache Sling Scripting GraphQL Scalars Provider",
+ Constants.SERVICE_VENDOR + "=The Apache Software Foundation" })
+public class SlingScalarsProvider {
+
+ static class URLCoercing implements Coercing<URL, String> {
+ static final String NAME = "URL";
+
+ @Override
+ public String serialize(Object dataFetcherResult) throws CoercingSerializeException {
+ if(dataFetcherResult instanceof URL) {
+ return getClass().getSimpleName() + " says:" + ((URL)dataFetcherResult).toExternalForm();
+ }
+ throw new CoercingSerializeException("Unexpected serialize input " + dataFetcherResult);
+ }
+
+ @Override
+ public URL parseValue(Object input) throws CoercingParseValueException {
+ try {
+ return new URL(String.valueOf(input));
+ } catch(Exception e) {
+ throw new CoercingParseValueException("URL parsing failed ", e);
+ }
+ }
+
+ @Override
+ public URL parseLiteral(Object input) throws CoercingParseLiteralException {
+ if(input instanceof StringValue) {
+ return parseValue(((StringValue)input).getValue());
+
+ }
+ throw new CoercingSerializeException("Unexpected parse input " + input);
+ }
+
+ }
+
+ static class UppercaseStringCoercing implements Coercing<String, String> {
+ static final String NAME = "UppercaseString";
+
+ @Override
+ public String serialize(Object dataFetcherResult) throws CoercingSerializeException {
+ return String.valueOf(dataFetcherResult).toUpperCase();
+ }
+
+ @Override
+ public String parseValue(Object input) throws CoercingParseValueException {
+ throw new CoercingParseValueException("Parsing not implemented");
+ }
+
+ @Override
+ public String parseLiteral(Object input) throws CoercingParseLiteralException {
+ throw new CoercingParseValueException("Parsing not implemented");
+ }
+
+ }
+
+ private GraphQLScalarType getScalar(String name) {
+ if(URLCoercing.NAME.equals(name)) {
+ return GraphQLScalarType.newScalar()
+ .name(URLCoercing.NAME)
+ .description("TODO should be an OSGi service - hardcoded for initial tests")
+ .coercing(new URLCoercing())
+ .build()
+ ;
+ }
+ if(UppercaseStringCoercing.NAME.equals(name)) {
+ return GraphQLScalarType.newScalar()
+ .name(UppercaseStringCoercing.NAME)
+ .description("TODO should be an OSGi service - hardcoded for initial tests")
+ .coercing(new UppercaseStringCoercing())
+ .build()
+ ;
+ }
+ return null;
+ }
+
+ public Iterable<GraphQLScalarType> getScalars(Map<String,ScalarTypeDefinition> schemaScalars) {
+ // Using just the names for now, not sure why we'd need the ScalarTypeDefinitions
+ return schemaScalars.keySet().stream()
+ .map(this::getScalar)
+ .filter(it -> it != null)
+ .collect(Collectors.toList());
+ }
+
+}
diff --git a/src/main/java/org/apache/sling/graphql/core/scripting/GraphQLScriptEngine.java b/src/main/java/org/apache/sling/graphql/core/scripting/GraphQLScriptEngine.java
index 771620a..b7eaa57 100644
--- a/src/main/java/org/apache/sling/graphql/core/scripting/GraphQLScriptEngine.java
+++ b/src/main/java/org/apache/sling/graphql/core/scripting/GraphQLScriptEngine.java
@@ -65,7 +65,7 @@ public class GraphQLScriptEngine extends AbstractScriptEngine {
.get(SlingBindings.RESOURCE);
final String [] selectors = getRequestSelectors(resource);
final ExecutionResult result = q.executeQuery(factory.getSchemaProviders(), factory.getdataFetcherSelector(),
- resource, selectors, IOUtils.toString(reader), null);
+ factory.getScalarsProvider(), resource, selectors, IOUtils.toString(reader), null);
final PrintWriter out = (PrintWriter) context.getBindings(ScriptContext.ENGINE_SCOPE).get(SlingBindings.OUT);
jsonSerializer.sendJSON(out, result);
} catch(Exception e) {
diff --git a/src/main/java/org/apache/sling/graphql/core/scripting/GraphQLScriptEngineFactory.java b/src/main/java/org/apache/sling/graphql/core/scripting/GraphQLScriptEngineFactory.java
index bad7587..72e1d75 100644
--- a/src/main/java/org/apache/sling/graphql/core/scripting/GraphQLScriptEngineFactory.java
+++ b/src/main/java/org/apache/sling/graphql/core/scripting/GraphQLScriptEngineFactory.java
@@ -24,6 +24,7 @@ import javax.script.ScriptEngineFactory;
import org.apache.sling.scripting.api.AbstractScriptEngineFactory;
import org.apache.sling.graphql.core.engine.SlingDataFetcherSelector;
+import org.apache.sling.graphql.core.scalars.SlingScalarsProvider;
import org.apache.sling.graphql.core.schema.RankedSchemaProviders;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
@@ -55,6 +56,9 @@ public class GraphQLScriptEngineFactory extends AbstractScriptEngineFactory {
@Reference
private SlingDataFetcherSelector dataFetcherSelector;
+ @Reference
+ private SlingScalarsProvider scalarsProvider;
+
@Activate
private void activate(final GraphQLScriptEngineFactoryConfiguration config, final BundleContext ctx) {
setExtensions(config.extensions());
@@ -85,4 +89,8 @@ public class GraphQLScriptEngineFactory extends AbstractScriptEngineFactory {
return dataFetcherSelector;
}
+ SlingScalarsProvider getScalarsProvider() {
+ return scalarsProvider;
+ }
+
}
diff --git a/src/main/java/org/apache/sling/graphql/core/servlet/GraphQLServlet.java b/src/main/java/org/apache/sling/graphql/core/servlet/GraphQLServlet.java
index b2e0167..5d4a68a 100644
--- a/src/main/java/org/apache/sling/graphql/core/servlet/GraphQLServlet.java
+++ b/src/main/java/org/apache/sling/graphql/core/servlet/GraphQLServlet.java
@@ -31,6 +31,7 @@ import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.graphql.core.engine.GraphQLResourceQuery;
import org.apache.sling.graphql.core.json.JsonSerializer;
+import org.apache.sling.graphql.core.scalars.SlingScalarsProvider;
import org.apache.sling.graphql.core.engine.SlingDataFetcherSelector;
import org.apache.sling.graphql.core.schema.RankedSchemaProviders;
import org.osgi.service.component.annotations.Component;
@@ -98,6 +99,9 @@ public class GraphQLServlet extends SlingAllMethodsServlet {
@Reference
private SlingDataFetcherSelector dataFetcherSelector;
+ @Reference
+ private SlingScalarsProvider scalarsProvider;
+
private final JsonSerializer jsonSerializer = new JsonSerializer();
@Override
@@ -123,7 +127,7 @@ public class GraphQLServlet extends SlingAllMethodsServlet {
try {
final GraphQLResourceQuery q = new GraphQLResourceQuery();
- final ExecutionResult result = q.executeQuery(schemaProviders, dataFetcherSelector,
+ final ExecutionResult result = q.executeQuery(schemaProviders, dataFetcherSelector, scalarsProvider,
resource, request.getRequestPathInfo().getSelectors(), query, parser.getVariables());
jsonSerializer.sendJSON(response.getWriter(), result);
} catch(Exception ex) {
diff --git a/src/test/java/org/apache/sling/graphql/core/engine/CustomScalarsTest.java b/src/test/java/org/apache/sling/graphql/core/engine/CustomScalarsTest.java
index 933ef68..f3a17fc 100644
--- a/src/test/java/org/apache/sling/graphql/core/engine/CustomScalarsTest.java
+++ b/src/test/java/org/apache/sling/graphql/core/engine/CustomScalarsTest.java
@@ -21,16 +21,38 @@ package org.apache.sling.graphql.core.engine;
import static com.jayway.jsonpath.matchers.JsonPathMatchers.hasJsonPath;
import static org.junit.Assert.assertThat;
+
+import javax.script.ScriptException;
+
import static org.hamcrest.Matchers.equalTo;
+
+import org.apache.sling.graphql.core.mocks.AddressDataFetcher;
+import org.apache.sling.graphql.core.mocks.TestUtil;
import org.junit.Test;
public class CustomScalarsTest extends ResourceQueryTestBase {
+ protected String getTestSchemaName() {
+ return "scalars-schema";
+ }
+
+ protected void setupDataFetchers() {
+ TestUtil.registerSlingDataFetcher(context.bundleContext(), "scalars/address", new AddressDataFetcher());
+ }
+
@Test
- public void TODOdoesNotTestScalarsSoFar() throws Exception {
- final String json = queryJSON("{ currentResource { path resourceType } }");
- assertThat(json, hasJsonPath("$.data.currentResource"));
- assertThat(json, hasJsonPath("$.data.currentResource.path", equalTo(resource.getPath())));
- assertThat(json, hasJsonPath("$.data.currentResource.resourceType", equalTo(resource.getResourceType())));
+ public void urlScalar() throws Exception {
+ final String url = "http://www.perdu.com";
+ final String query = String.format("{ address (url: \"%s\") { url hostname } }", url);
+ final String json = queryJSON(query);
+ assertThat(json, hasJsonPath("$.data.address.hostname", equalTo("WWW.PERDU.COM")));
+ assertThat(json, hasJsonPath("$.data.address.url", equalTo("URLCoercing says:" + url)));
+ }
+
+ @Test(expected = ScriptException.class)
+ public void urlSyntaxError() throws Exception {
+ final String url = "This is not an URL!";
+ final String query = String.format("{ address (url: \"%s\") { url hostname } }", url);
+ queryJSON(query);
}
}
\ No newline at end of file
diff --git a/src/test/java/org/apache/sling/graphql/core/engine/GraphQLResourceQueryTest.java b/src/test/java/org/apache/sling/graphql/core/engine/GraphQLResourceQueryTest.java
index e699566..6cc707c 100644
--- a/src/test/java/org/apache/sling/graphql/core/engine/GraphQLResourceQueryTest.java
+++ b/src/test/java/org/apache/sling/graphql/core/engine/GraphQLResourceQueryTest.java
@@ -27,14 +27,30 @@ import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import java.io.IOException;
+import java.util.Dictionary;
+import java.util.Hashtable;
+
import org.apache.sling.graphql.core.mocks.DigestDataFetcher;
import org.apache.sling.graphql.core.mocks.EchoDataFetcher;
+import org.apache.sling.graphql.core.mocks.FailingDataFetcher;
import org.apache.sling.graphql.core.mocks.MockSchemaProvider;
import org.apache.sling.graphql.core.mocks.TestUtil;
import org.junit.Test;
import org.osgi.framework.ServiceRegistration;
public class GraphQLResourceQueryTest extends ResourceQueryTestBase {
+
+ protected void setupDataFetchers() {
+ final Dictionary<String, Object> staticData = new Hashtable<>();
+ staticData.put("test", true);
+
+ TestUtil.registerSlingDataFetcher(context.bundleContext(), "echoNS/echo", new EchoDataFetcher(null));
+ TestUtil.registerSlingDataFetcher(context.bundleContext(), "failure/fail", new FailingDataFetcher());
+ TestUtil.registerSlingDataFetcher(context.bundleContext(), "test/static", new EchoDataFetcher(staticData));
+ TestUtil.registerSlingDataFetcher(context.bundleContext(), "test/fortyTwo", new EchoDataFetcher(42));
+ TestUtil.registerSlingDataFetcher(context.bundleContext(), "sling/digest", new DigestDataFetcher());
+ }
+
@Test
public void basicTest() throws Exception {
final String json = queryJSON("{ currentResource { path resourceType } }");
@@ -76,7 +92,7 @@ public class GraphQLResourceQueryTest extends ResourceQueryTestBase {
public void dataFetcherFailureTest() throws Exception {
try {
final String stmt = "{ currentResource { failure } }";
- new GraphQLResourceQuery().executeQuery(schemaProvider, dataFetchersSelector, resource, null, stmt, null);
+ new GraphQLResourceQuery().executeQuery(schemaProvider, dataFetchersSelector, scalarsProvider, resource, null, stmt, null);
} catch(RuntimeException rex) {
assertThat(rex.getMessage(), equalTo("FailureDataFetcher"));
}
diff --git a/src/test/java/org/apache/sling/graphql/core/engine/ResourceQueryTestBase.java b/src/test/java/org/apache/sling/graphql/core/engine/ResourceQueryTestBase.java
index b5a4598..6df9d72 100644
--- a/src/test/java/org/apache/sling/graphql/core/engine/ResourceQueryTestBase.java
+++ b/src/test/java/org/apache/sling/graphql/core/engine/ResourceQueryTestBase.java
@@ -34,6 +34,7 @@ import org.apache.sling.graphql.core.mocks.FailingDataFetcher;
import org.apache.sling.graphql.core.mocks.MockSchemaProvider;
import org.apache.sling.graphql.core.mocks.MockScriptServlet;
import org.apache.sling.graphql.core.mocks.TestUtil;
+import org.apache.sling.graphql.core.scalars.SlingScalarsProvider;
import org.junit.Before;
import org.junit.Rule;
import org.mockito.Mockito;
@@ -43,6 +44,7 @@ import graphql.ExecutionResult;
public abstract class ResourceQueryTestBase {
protected SchemaProvider schemaProvider;
protected SlingDataFetcherSelector dataFetchersSelector;
+ protected SlingScalarsProvider scalarsProvider = new SlingScalarsProvider();
protected Resource resource;
@Rule
@@ -50,21 +52,14 @@ public abstract class ResourceQueryTestBase {
@Before
public void setup() {
- schemaProvider = new MockSchemaProvider("test-schema");
+ schemaProvider = new MockSchemaProvider(getTestSchemaName());
final String resourceType = "RT-" + UUID.randomUUID();
final String path = "/some/path/" + UUID.randomUUID();
resource = Mockito.mock(Resource.class);
Mockito.when(resource.getPath()).thenReturn(path);
Mockito.when(resource.getResourceType()).thenReturn(resourceType);
- final Dictionary<String, Object> staticData = new Hashtable<>();
- staticData.put("test", true);
-
- TestUtil.registerSlingDataFetcher(context.bundleContext(), "echoNS/echo", new EchoDataFetcher(null));
- TestUtil.registerSlingDataFetcher(context.bundleContext(), "failure/fail", new FailingDataFetcher());
- TestUtil.registerSlingDataFetcher(context.bundleContext(), "test/static", new EchoDataFetcher(staticData));
- TestUtil.registerSlingDataFetcher(context.bundleContext(), "test/fortyTwo", new EchoDataFetcher(42));
- TestUtil.registerSlingDataFetcher(context.bundleContext(), "sling/digest", new DigestDataFetcher());
+ setupDataFetchers();
// Our MockScriptServlet to simulates a script for unit tests, for the
// integration tests we use a real script
@@ -84,8 +79,15 @@ public abstract class ResourceQueryTestBase {
protected String queryJSON(String stmt, String [] selectors) throws Exception {
final ExecutionResult result = new GraphQLResourceQuery().executeQuery(schemaProvider,
- dataFetchersSelector, resource, selectors, stmt, null);
+ dataFetchersSelector, scalarsProvider, resource, selectors, stmt, null);
assertTrue("Expecting no errors: " + result.getErrors(), result.getErrors().isEmpty());
return new JsonSerializer().toJSON(result);
}
+
+ protected void setupDataFetchers() {
+ }
+
+ protected String getTestSchemaName() {
+ return "test-schema";
+ }
}
\ No newline at end of file
diff --git a/src/test/java/org/apache/sling/graphql/core/engine/CustomScalarsTest.java b/src/test/java/org/apache/sling/graphql/core/mocks/AddressDataFetcher.java
similarity index 52%
copy from src/test/java/org/apache/sling/graphql/core/engine/CustomScalarsTest.java
copy to src/test/java/org/apache/sling/graphql/core/mocks/AddressDataFetcher.java
index 933ef68..88824aa 100644
--- a/src/test/java/org/apache/sling/graphql/core/engine/CustomScalarsTest.java
+++ b/src/test/java/org/apache/sling/graphql/core/mocks/AddressDataFetcher.java
@@ -16,21 +16,28 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.sling.graphql.core.engine;
-import static com.jayway.jsonpath.matchers.JsonPathMatchers.hasJsonPath;
+package org.apache.sling.graphql.core.mocks;
-import static org.junit.Assert.assertThat;
-import static org.hamcrest.Matchers.equalTo;
-import org.junit.Test;
+import java.net.URL;
+import java.util.Dictionary;
+import java.util.Hashtable;
-public class CustomScalarsTest extends ResourceQueryTestBase {
- @Test
- public void TODOdoesNotTestScalarsSoFar() throws Exception {
- final String json = queryJSON("{ currentResource { path resourceType } }");
- assertThat(json, hasJsonPath("$.data.currentResource"));
- assertThat(json, hasJsonPath("$.data.currentResource.path", equalTo(resource.getPath())));
- assertThat(json, hasJsonPath("$.data.currentResource.resourceType", equalTo(resource.getResourceType())));
- }
+import org.apache.sling.graphql.api.SlingDataFetcher;
+import org.apache.sling.graphql.api.SlingDataFetcherEnvironment;
+
+public class AddressDataFetcher implements SlingDataFetcher<Object> {
-}
\ No newline at end of file
+ @Override
+ public Object get(SlingDataFetcherEnvironment e) throws Exception {
+ final Object p = e.getArgument("url");
+ if(p instanceof URL) {
+ final URL url = (URL)p;
+ final Dictionary<String, Object> result = new Hashtable<>();
+ result.put("url", url);
+ result.put("hostname", url.getHost());
+ return result;
+ }
+ return null;
+ }
+}
diff --git a/src/test/java/org/apache/sling/graphql/core/schema/SchemaDescriptionsTest.java b/src/test/java/org/apache/sling/graphql/core/schema/SchemaDescriptionsTest.java
index 357b736..f72fdb7 100644
--- a/src/test/java/org/apache/sling/graphql/core/schema/SchemaDescriptionsTest.java
+++ b/src/test/java/org/apache/sling/graphql/core/schema/SchemaDescriptionsTest.java
@@ -36,6 +36,7 @@ import org.apache.sling.graphql.core.engine.ScriptedDataFetcherProvider;
import org.apache.sling.graphql.core.engine.SlingDataFetcherSelector;
import org.apache.sling.graphql.core.json.JsonSerializer;
import org.apache.sling.graphql.core.mocks.MockSchemaProvider;
+import org.apache.sling.graphql.core.scalars.SlingScalarsProvider;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@@ -55,6 +56,7 @@ import net.minidev.json.JSONArray;
public class SchemaDescriptionsTest {
private SchemaProvider schemaProvider = new MockSchemaProvider("test-schema");
private SlingDataFetcherSelector dataFetchersSelector;
+ private SlingScalarsProvider scalarsProvider;
private Resource resource;
private String schemaJson;
@@ -105,12 +107,14 @@ public class SchemaDescriptionsTest {
context.registerInjectActivateService(new ScriptedDataFetcherProvider());
context.registerInjectActivateService(new SlingDataFetcherSelector());
dataFetchersSelector = context.getService(SlingDataFetcherSelector.class);
+ context.registerInjectActivateService(new SlingScalarsProvider());
+ scalarsProvider = context.getService(SlingScalarsProvider.class);
schemaJson = queryJSON(SCHEMA_QUERY);
}
private String queryJSON(String stmt) throws Exception {
final ExecutionResult result = new GraphQLResourceQuery().executeQuery(schemaProvider,
- dataFetchersSelector, resource, null, stmt, null);
+ dataFetchersSelector, scalarsProvider, resource, null, stmt, null);
assertTrue("Expecting no errors: " + result.getErrors(), result.getErrors().isEmpty());
return new JsonSerializer().toJSON(result);
}
diff --git a/src/test/resources/scalars-schema.txt b/src/test/resources/scalars-schema.txt
new file mode 100644
index 0000000..75851ff
--- /dev/null
+++ b/src/test/resources/scalars-schema.txt
@@ -0,0 +1,35 @@
+# * Licensed to the Apache Software Foundation (ASF) under one
+# * or more contributor license agreements. See the NOTICE file
+# * distributed with this work for additional information
+# * regarding copyright ownership. The ASF licenses this file
+# * to you under the Apache License, Version 2.0 (the
+# * "License"); you may not use this file except in compliance
+# * with the License. You may obtain a copy of the License at
+# *
+# * http://www.apache.org/licenses/LICENSE-2.0
+# *
+# * Unless required by applicable law or agreed to in writing,
+# * software distributed under the License is distributed on an
+# * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# * KIND, either express or implied. See the License for the
+# * specific language governing permissions and limitations
+# * under the License.
+
+# This directive maps fields to our Sling data fetchers
+directive @fetcher(
+ name : String,
+ options : String = "",
+ source : String = ""
+) on FIELD_DEFINITION
+
+scalar URL
+scalar UppercaseString
+
+type Query {
+ address (url : URL) : AddressInfo @fetcher(name:"scalars/address")
+}
+
+type AddressInfo {
+ hostname: UppercaseString
+ url: URL
+}
\ No newline at end of file