All Downloads are FREE. Search and download functionalities are using the official Maven repository.

graphql.servlet.GraphQLObjectMapper Maven / Gradle / Ivy

There is a newer version: 6.1.3
Show newest version
package graphql.servlet;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.InjectableValues;
import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import graphql.ExecutionResult;
import graphql.ExecutionResultImpl;
import graphql.GraphQLError;
import graphql.servlet.internal.GraphQLRequest;
import graphql.servlet.internal.VariablesDeserializer;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

/**
 * @author Andrew Potter
 */
public class GraphQLObjectMapper {
    private final Supplier objectMapperConfigurerSupplier;
    private final Supplier graphQLErrorHandlerSupplier;

    private volatile ObjectMapper mapper;

    protected GraphQLObjectMapper(Supplier objectMapperConfigurerSupplier, Supplier graphQLErrorHandlerSupplier) {
        this.objectMapperConfigurerSupplier = objectMapperConfigurerSupplier;
        this.graphQLErrorHandlerSupplier = graphQLErrorHandlerSupplier;
    }

    // Double-check idiom for lazy initialization of instance fields.
    public ObjectMapper getJacksonMapper() {
        ObjectMapper result = mapper;
        if (result == null) { // First check (no locking)
            synchronized(this) {
                result = mapper;
                if (result == null) // Second check (with locking)
                    mapper = result = createObjectMapper();
            }
        }

        return result;
    }

    private ObjectMapper createObjectMapper() {
        ObjectMapper mapper = new ObjectMapper().disable(SerializationFeature.FAIL_ON_EMPTY_BEANS).registerModule(new Jdk8Module());
        objectMapperConfigurerSupplier.get().configure(mapper);

        InjectableValues.Std injectableValues = new InjectableValues.Std();
        injectableValues.addValue(ObjectMapper.class, mapper);
        mapper.setInjectableValues(injectableValues);

        return mapper;
    }

    /**
     * @return an {@link ObjectReader} for deserializing {@link GraphQLRequest}
     */
    public ObjectReader getGraphQLRequestMapper() {
        return getJacksonMapper().reader().forType(GraphQLRequest.class);
    }

    public GraphQLRequest readGraphQLRequest(InputStream inputStream) throws IOException {
        return getGraphQLRequestMapper().readValue(inputStream);
    }

    public GraphQLRequest readGraphQLRequest(String text) throws IOException {
        return getGraphQLRequestMapper().readValue(text);
    }

    public List readBatchedGraphQLRequest(InputStream inputStream) throws IOException {
        MappingIterator iterator = getGraphQLRequestMapper().readValues(inputStream);
        List requests = new ArrayList<>();

        while (iterator.hasNext()) {
            requests.add(iterator.next());
        }

        return requests;
    }

    public List readBatchedGraphQLRequest(String query) throws IOException {
        MappingIterator iterator = getGraphQLRequestMapper().readValues(query);
        List requests = new ArrayList<>();

        while (iterator.hasNext()) {
            requests.add(iterator.next());
        }

        return requests;
    }

    public String serializeResultAsJson(ExecutionResult executionResult) {
        try {
            return getJacksonMapper().writeValueAsString(createResultFromExecutionResult(executionResult));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public boolean areErrorsPresent(ExecutionResult executionResult) {
        return graphQLErrorHandlerSupplier.get().errorsPresent(executionResult.getErrors());
    }

    public ExecutionResult sanitizeErrors(ExecutionResult executionResult) {
        Object data = executionResult.getData();
        Map extensions = executionResult.getExtensions();
        List errors = executionResult.getErrors();

        GraphQLErrorHandler errorHandler = graphQLErrorHandlerSupplier.get();
        if(errorHandler.errorsPresent(errors)) {
            errors = errorHandler.processErrors(errors);
        } else {
            errors = null;
        }

        return new ExecutionResultImpl(data, errors, extensions);
    }

    public Map createResultFromExecutionResult(ExecutionResult executionResult) {
        return convertSanitizedExecutionResult(sanitizeErrors(executionResult));
    }

    public Map convertSanitizedExecutionResult(ExecutionResult executionResult) {
        return convertSanitizedExecutionResult(executionResult, true);
    }

    public Map convertSanitizedExecutionResult(ExecutionResult executionResult, boolean includeData) {
        final Map result = new LinkedHashMap<>();

        if(includeData) {
            result.put("data", executionResult.getData());
        }

        if (areErrorsPresent(executionResult)) {
            result.put("errors", executionResult.getErrors());
        }

        if(executionResult.getExtensions() != null){
            result.put("extensions", executionResult.getExtensions());
        }

        return result;
    }

    public Map deserializeVariables(String variables) {
        try {
            return VariablesDeserializer.deserializeVariablesObject(getJacksonMapper().readValue(variables, Object.class), getJacksonMapper());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static Builder newBuilder() {
        return new Builder();
    }

    public static class Builder {
        private Supplier objectMapperConfigurer = DefaultObjectMapperConfigurer::new;
        private Supplier graphQLErrorHandler = DefaultGraphQLErrorHandler::new;

        public Builder withObjectMapperConfigurer(ObjectMapperConfigurer objectMapperConfigurer) {
            return withObjectMapperConfigurer(() -> objectMapperConfigurer);
        }

        public Builder withObjectMapperConfigurer(Supplier objectMapperConfigurer) {
            this.objectMapperConfigurer = objectMapperConfigurer;
            return this;
        }

        public Builder withGraphQLErrorHandler(GraphQLErrorHandler graphQLErrorHandler) {
            return withGraphQLErrorHandler(() -> graphQLErrorHandler);
        }

        public Builder withGraphQLErrorHandler(Supplier graphQLErrorHandler) {
            this.graphQLErrorHandler = graphQLErrorHandler;
            return this;
        }

        public GraphQLObjectMapper build() {
            return new GraphQLObjectMapper(objectMapperConfigurer, graphQLErrorHandler);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy