Skip to content
This repository was archived by the owner on Dec 19, 2023. It is now read-only.

Add support for two graphiql headers configurations #484

Merged
merged 9 commits into from
Dec 19, 2020
Merged
Show file tree
Hide file tree
Changes from all 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
29 changes: 29 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,32 @@ jobs:
BINTRAY_USER: ${{ secrets.BINTRAY_USER }}
BINTRAY_PASS: ${{ secrets.BINTRAY_PASSWORD }}
run: ./gradlew artifactoryPublish -Dsnapshot=true -Dbuild.number=${{ env.GITHUB_RUN_NUMBER }}
sonar:
name: Sonar analysis
needs: validation
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
- name: Set up JDK 11
uses: actions/setup-java@v1
with:
java-version: 11
- name: Cache SonarCloud packages
uses: actions/cache@v1
with:
path: ~/.sonar/cache
key: ${{ runner.os }}-sonar
restore-keys: ${{ runner.os }}-sonar
- name: Cache Gradle packages
uses: actions/cache@v1
with:
path: ~/.gradle/caches
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }}
restore-keys: ${{ runner.os }}-gradle
- name: Build and analyze
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
run: ./gradlew build jacocoTestReport sonarqube --info
37 changes: 37 additions & 0 deletions .github/workflows/pull-request.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ on:
branches-ignore:
- master
pull_request:
types: [opened, synchronize, reopened]

jobs:
validation:
Expand Down Expand Up @@ -49,3 +50,39 @@ jobs:
if: matrix.os == 'windows-latest'
shell: cmd
run: gradlew --info check
build:
name: Sonar analysis
needs: validation
runs-on: ubuntu-latest
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
steps:
- uses: actions/checkout@v2
if: env.SONAR_TOKEN != null
with:
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
- name: Set up JDK 11
if: env.SONAR_TOKEN != null
uses: actions/setup-java@v1
with:
java-version: 11
- name: Cache SonarCloud packages
if: env.SONAR_TOKEN != null
uses: actions/cache@v1
with:
path: ~/.sonar/cache
key: ${{ runner.os }}-sonar
restore-keys: ${{ runner.os }}-sonar
- name: Cache Gradle packages
if: env.SONAR_TOKEN != null
uses: actions/cache@v1
with:
path: ~/.gradle/caches
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }}
restore-keys: ${{ runner.os }}-gradle
- name: Build and analyze
if: env.SONAR_TOKEN != null
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
run: ./gradlew build jacocoTestReport sonarqube --info
20 changes: 20 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,22 @@ plugins {
id 'net.researchgate.release' version "$LIB_RELEASE_PLUGIN_VER"
id "org.springframework.boot" version "$LIB_SPRING_BOOT_VER" apply false
id "com.jfrog.artifactory" version "4.15.1" apply false
id "org.sonarqube" version "3.0"
id "jacoco"
}

sonarqube {
properties {
property "sonar.projectKey", "graphql-java-kickstart_graphql-spring-boot"
property "sonar.organization", "graphql-java-kickstart"
property "sonar.host.url", "https://sonarcloud.io"
}
}

subprojects {
apply plugin: 'idea'
apply plugin: 'jacoco'
apply plugin: 'org.sonarqube'
apply plugin: 'java'
apply plugin: 'java-library'
apply plugin: 'maven-publish'
Expand Down Expand Up @@ -76,6 +88,14 @@ subprojects {
}
}

jacocoTestReport {
reports {
xml.enabled = true
html.enabled = false
csv.enabled = false
}
}

idea {
module {
downloadJavadoc = true
Expand Down
8 changes: 7 additions & 1 deletion example/src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,14 @@ altair:
graphiql:
enabled: true
cdn:
enabled: true
enabled: false
version: 0.17.5
headers:
Test: TestHeader
props:
variables:
headerEditorEnabled: true
headers: '{ "Authorization": "SomeValue" }'
voyager:
enabled: true
cdn:
Expand Down
6 changes: 3 additions & 3 deletions gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@ TARGET_COMPATIBILITY = 1.8
### Dependencies

LIB_GRAPHQL_JAVA_VER = 15.0
LIB_SPRING_BOOT_VER = 2.3.4.RELEASE
LIB_GRAPHQL_SERVLET_VER = 10.0.0
LIB_GRAPHQL_JAVA_TOOLS_VER = 6.2.0
LIB_SPRING_BOOT_VER = 2.3.6.RELEASE
LIB_GRAPHQL_SERVLET_VER = 10.1.0-SNAPSHOT
LIB_GRAPHQL_JAVA_TOOLS_VER = 6.3.0
LIB_GRAPHQL_ANNOTATIONS_VER = 8.2
LIB_REFLECTIONS_VER = 0.9.11
LIB_APACHE_COMMONS_TEXT=1.8
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,23 @@

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.StrSubstitutor;
import org.apache.commons.text.StringSubstitutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
* @author Andrew Potter
*/
Expand Down Expand Up @@ -61,17 +59,10 @@ private void loadProps() throws IOException {
private void loadHeaders() {
PropertyGroupReader propertyReader = new PropertyGroupReader(environment, "graphiql.headers.");
headerProperties = propertyReader.load();
addIfAbsent(headerProperties, "Accept");
addIfAbsent(headerProperties, "Content-Type");
}

private void addIfAbsent(Properties headerProperties, String header) {
if (!headerProperties.containsKey(header)) {
headerProperties.setProperty(header, MediaType.APPLICATION_JSON_VALUE);
}
}

public byte[] graphiql(String contextPath, @PathVariable Map<String, String> params, Object csrf) {
public byte[] graphiql(String contextPath, @PathVariable Map<String, String> params,
Object csrf) {
if (csrf != null) {
CsrfToken csrfToken = (CsrfToken) csrf;
headerProperties.setProperty(csrfToken.getHeaderName(), csrfToken.getToken());
Expand All @@ -83,7 +74,7 @@ public byte[] graphiql(String contextPath, @PathVariable Map<String, String> par
contextPath + graphiQLProperties.getSTATIC().getBasePath()
);

String populatedTemplate = StrSubstitutor.replace(template, replacements);
String populatedTemplate = StringSubstitutor.replace(template, replacements);
return populatedTemplate.getBytes(Charset.defaultCharset());
}

Expand All @@ -97,7 +88,8 @@ private Map<String, String> getReplacements(
replacements.put("subscriptionsEndpoint", subscriptionsEndpoint);
replacements.put("staticBasePath", staticBasePath);
replacements.put("pageTitle", graphiQLProperties.getPageTitle());
replacements.put("pageFavicon", getResourceUrl(staticBasePath, "favicon.ico", FAVICON_GRAPHQL_ORG));
replacements
.put("pageFavicon", getResourceUrl(staticBasePath, "favicon.ico", FAVICON_GRAPHQL_ORG));
replacements.put("es6PromiseJsUrl", getResourceUrl(staticBasePath, "es6-promise.auto.min.js",
joinCdnjsPath("es6-promise", "4.1.1", "es6-promise.auto.min.js")));
replacements.put("fetchJsUrl", getResourceUrl(staticBasePath, "fetch.min.js",
Expand All @@ -123,9 +115,11 @@ private Map<String, String> getReplacements(
log.error("Cannot serialize headers", e);
}
replacements
.put("subscriptionClientTimeout", String.valueOf(graphiQLProperties.getSubscriptions().getTimeout() * 1000));
.put("subscriptionClientTimeout",
String.valueOf(graphiQLProperties.getSubscriptions().getTimeout() * 1000));
replacements
.put("subscriptionClientReconnect", String.valueOf(graphiQLProperties.getSubscriptions().isReconnect()));
.put("subscriptionClientReconnect",
String.valueOf(graphiQLProperties.getSubscriptions().isReconnect()));
replacements.put("editorThemeCss", getEditorThemeCssURL());
return replacements;
}
Expand Down Expand Up @@ -161,7 +155,8 @@ private String joinJsDelivrPath(String library, String cdnVersion, String cdnFil
return CDN_JSDELIVR_NET_NPM + library + "@" + cdnVersion + "/" + cdnFileName;
}

private String constructGraphQlEndpoint(String contextPath, @RequestParam Map<String, String> params) {
private String constructGraphQlEndpoint(String contextPath,
@RequestParam Map<String, String> params) {
String endpoint = graphiQLProperties.getEndpoint().getGraphql();
for (Map.Entry<String, String> param : params.entrySet()) {
endpoint = endpoint.replaceAll("\\{" + param.getKey() + "}", param.getValue());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,12 +101,22 @@

var headers = ${headers}

function addRequiredHeadersIfAbsent() {
if (!headers['Accept']) {
headers['Accept'] = 'application/json'
}
if (!headers['Content-Type']) {
headers['Content-Type'] = 'application/json'
}
}

function onEditHeaders(newHeaders) {
try {
headers = JSON.parse(newHeaders)
} catch(e) {
headers = {}
}
addRequiredHeadersIfAbsent()
}

// Defines a GraphQL fetcher using the fetch API. You're not required to
Expand Down Expand Up @@ -162,8 +172,13 @@
props.onEditVariables = onEditVariables
props.onEditOperationName = onEditOperationName
props.onEditHeaders = onEditHeaders
props.headers = props.headers || '{}'
if (headers) {
var newHeaders = Object.assign({}, JSON.parse(props.headers), headers)
props.headers = JSON.stringify(newHeaders, undefined, 2)
}
onEditHeaders(props.headers)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

calling onEditHeaders(props.headers) seems to be necessary here, otherwise the headers are not sent with the request (until the onEditHeaders event is triggered)

Also, two additonal headers are appearing on the "Request headers" tab: "Accept": "application/json" and "Content-Type": "application/json"

Copy link
Member Author

@oliemansm oliemansm Nov 30, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Those two additional headers are added by the GraphiQLController atm because otherwise it would send the request as just plain text:

Accept: */*
Content-Type: text/plain;charset=UTF-8

According to GraphQL Specification it should use Content-Type application/json in that case.

I could add them "silently" though, so instead of adding them in the headers tab too, only add them if there absent.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the "silent" solution is better in this case, since these headers are/should be always the same. (And the user still has the option to customize them by adding them manually.)

console.debug(props)
// Render <GraphiQL /> into the body.
ReactDOM.render(
React.createElement(GraphiQL, props),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,7 @@ public Object graphqlPOST(
throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY, "Could not process GraphQL request");
}

@GetMapping(value = "${graphql.url:graphql}",
produces = MediaType.APPLICATION_JSON_VALUE)
@GetMapping(value = "${graphql.url:graphql}", produces = MediaType.APPLICATION_JSON_VALUE)
public Object graphqlGET(
@Nullable @RequestParam("query") String query,
@Nullable @RequestParam(value = "operationName", required = false) String operationName,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,6 @@ public GraphQLConfiguration graphQLServletConfiguration(GraphQLInvocationInputFa
.with(queryInvoker)
.with(graphQLObjectMapper)
.with(listeners)
.with(graphQLServletProperties.isAsyncModeEnabled())
.with(graphQLServletProperties.getSubscriptionTimeout())
.with(batchInputPreProcessor)
.with(graphQLServletProperties.getContextSetting())
Expand Down
Loading