graphql.execution.DataFetcherResult Java Examples

The following examples show how to use graphql.execution.DataFetcherResult. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractDataFetcher.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
protected final DataFetcherResult.Builder<Object> appendPartialResult(
        DataFetcherResult.Builder<Object> resultBuilder,
        DataFetchingEnvironment dfe,
        GraphQLException graphQLException) {
    DataFetcherExceptionHandlerParameters handlerParameters = DataFetcherExceptionHandlerParameters
            .newExceptionParameters()
            .dataFetchingEnvironment(dfe)
            .exception(graphQLException)
            .build();

    SourceLocation sourceLocation = handlerParameters.getSourceLocation();
    ExecutionPath path = handlerParameters.getPath();
    GraphQLExceptionWhileDataFetching error = new GraphQLExceptionWhileDataFetching(path, graphQLException,
            sourceLocation);

    return resultBuilder
            .data(graphQLException.getPartialResults())
            .error(error);
}
 
Example #2
Source File: TransformException.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
@Override
public DataFetcherResult.Builder<Object> appendDataFetcherResult(DataFetcherResult.Builder<Object> builder,
        DataFetchingEnvironment dfe) {
    DataFetcherExceptionHandlerParameters handlerParameters = DataFetcherExceptionHandlerParameters
            .newExceptionParameters()
            .dataFetchingEnvironment(dfe)
            .exception(super.getCause())
            .build();

    SourceLocation sourceLocation = getSourceLocation(dfe, handlerParameters);

    List<String> paths = toPathList(handlerParameters.getPath());

    ValidationError error = new ValidationError(ValidationErrorType.WrongType,
            sourceLocation, "argument '" + field.getName() + "' with value 'StringValue{value='" + parameterValue
                    + "'}' is not a valid '" + getScalarTypeName() + "'",
            paths);

    return builder.error(error);
}
 
Example #3
Source File: ResolutionEnvironment.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <T, S> S convertOutput(T output, AnnotatedElement element, AnnotatedType type) {
    if (output == null) {
        return null;
    }

    // Transparently handle unexpected wrapped results. This enables elegant exception handling, partial results etc.
    if (DataFetcherResult.class.equals(output.getClass()) && !DataFetcherResult.class.equals(resolver.getRawReturnType())) {
        DataFetcherResult<?> result = (DataFetcherResult<?>) output;
        if (result.getData() != null) {
            Object convertedData = convert(result.getData(), element, type);
            return (S) DataFetcherResult.newResult()
                    .data(convertedData)
                    .errors(result.getErrors())
                    .localContext(result.getLocalContext())
                    .mapRelativeErrors(result.isMapRelativeErrors())
                    .build();
        }
    }

    return convert(output, element, type);
}
 
Example #4
Source File: FederatedTracingInstrumentation.java    From federation-jvm with MIT License 5 votes vote down vote up
@NotNull
private List<GraphQLError> convertErrors(Throwable throwable, Object result) {
    ArrayList<GraphQLError> graphQLErrors = new ArrayList<>();

    if (throwable != null) {
        if (throwable instanceof GraphQLError) {
            graphQLErrors.add((GraphQLError) throwable);
        } else {
            String message = throwable.getMessage();
            if (message == null) {
                message = "(null)";
            }
            GraphqlErrorBuilder errorBuilder = GraphqlErrorBuilder.newError()
                    .message(message);

            if (throwable instanceof InvalidSyntaxException) {
                errorBuilder.location(((InvalidSyntaxException) throwable).getLocation());
            }

            graphQLErrors.add(errorBuilder.build());
        }
    }

    if (result instanceof DataFetcherResult<?>) {
        DataFetcherResult<?> theResult = (DataFetcherResult) result;
        if (theResult.hasErrors()) {
            graphQLErrors.addAll(theResult.getErrors());
        }
    }

    return graphQLErrors;
}
 
Example #5
Source File: ReflectionDataFetcher.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
/**
 * This makes the call on the method. We do the following:
 * 1) Get the correct instance of the class we want to make the call in using CDI. That allow the developer to still use
 * Scopes in the bean.
 * 2) Get the argument values (if any) from graphql-java and make sue they are in the correct type, and if needed,
 * transformed.
 * 3) Make a call on the method with the correct arguments
 * 4) get the result and if needed transform it before we return it.
 * 
 * @param dfe the Data Fetching Environment from graphql-java
 * @return the result from the call.
 */
@Override
public DataFetcherResult<Object> get(DataFetchingEnvironment dfe) throws Exception {
    //TODO: custom context object?
    final GraphQLContext context = GraphQLContext.newContext().build();
    final DataFetcherResult.Builder<Object> resultBuilder = DataFetcherResult.newResult().localContext(context);

    Class<?> operationClass = classloadingService.loadClass(operation.getClassName());
    Object declaringObject = lookupService.getInstance(operationClass);
    Method m = getMethod(operationClass);

    try {
        Object[] transformedArguments = argumentHelper.getArguments(dfe);

        ExecutionContextImpl executionContext = new ExecutionContextImpl(declaringObject, m, transformedArguments, context,
                dfe,
                decorators.iterator());

        Object resultFromMethodCall = execute(executionContext);

        // See if we need to transform on the way out
        resultBuilder.data(fieldHelper.transformResponse(resultFromMethodCall));
    } catch (AbstractDataFetcherException pe) {
        //Arguments or result couldn't be transformed
        pe.appendDataFetcherResult(resultBuilder, dfe);
    } catch (GraphQLException graphQLException) {
        appendPartialResult(resultBuilder, dfe, graphQLException);
    } catch (SecurityException | IllegalAccessException | IllegalArgumentException ex) {
        //m.invoke failed
        throw msg.dataFetcherException(operation, ex);
    }

    return resultBuilder.build();
}
 
Example #6
Source File: Util.java    From samples with MIT License 5 votes vote down vote up
public static Object mkDFRFromFetchedResult(List<GraphQLError> errors, Object value) {
  if (value instanceof CompletionStage) {
    return ((CompletionStage<?>) value).thenApply(v -> mkDFRFromFetchedResult(errors, v));
  } else if (value instanceof DataFetcherResult) {
    DataFetcherResult df = (DataFetcherResult) value;
    return mkDFR(df.getData(), concat(errors, df.getErrors()), df.getLocalContext());
  } else {
    return mkDFR(value, errors, null);
  }
}
 
Example #7
Source File: PublisherAdapter.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
private <R> CompletableFuture<DataFetcherResult<List<R>>> collect(Publisher<R> publisher, ExecutionStepInfo step) {
    CompletableFuture<DataFetcherResult<List<R>>> promise = new CompletableFuture<>();

    executor.execute(() -> publisher.subscribe(new Subscriber<R>() {

        private List<R> buffer = new ArrayList<>();

        @Override
        public void onSubscribe(Subscription subscription) {
            subscription.request(Long.MAX_VALUE);
        }

        @Override
        public void onNext(R result) {
            buffer.add(result);
        }

        @Override
        public void onError(Throwable error) {
            ExceptionWhileDataFetching wrapped = new ExceptionWhileDataFetching(step.getPath(), error, step.getField().getSingleField().getSourceLocation());
            promise.complete(DataFetcherResult.<List<R>>newResult()
                    .data(buffer)
                    .error(wrapped)
                    .build());
        }

        @Override
        public void onComplete() {
            promise.complete(DataFetcherResult.<List<R>>newResult().data(buffer).build());
        }
    }));
    return promise;
}
 
Example #8
Source File: ConversionTest.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Override
public Object aroundInvoke(InvocationContext context, ResolverInterceptor.Continuation continuation) throws Exception {
    return DataFetcherResult.newResult()
            .data(continuation.proceed(context))
            .error(GraphqlErrorBuilder.newError(context.getResolutionEnvironment().dataFetchingEnvironment)
                    .message("Test error")
                    .errorType(ErrorType.DataFetchingException)
                    .build())
            .build();
}
 
Example #9
Source File: AbstractDataFetcherException.java    From smallrye-graphql with Apache License 2.0 4 votes vote down vote up
public abstract DataFetcherResult.Builder<Object> appendDataFetcherResult(DataFetcherResult.Builder<Object> builder,
DataFetchingEnvironment dfe);
 
Example #10
Source File: Util.java    From samples with MIT License 4 votes vote down vote up
public static DataFetcherResult<Object> mkDFR(Object value, List<GraphQLError> errors, Object localContext) {
return DataFetcherResult.newResult().data(value).errors(errors).localContext(localContext).build();
}
 
Example #11
Source File: DataFetcherResultMapper.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
@Override
public GraphQLInputType toGraphQLInputType(AnnotatedType javaType, Set<Class<? extends TypeMapper>> mappersToSkip, TypeMappingEnvironment env) {
    throw new UnsupportedOperationException(DataFetcherResult.class.getSimpleName() + " can not be used as an input type");
}
 
Example #12
Source File: DataFetcherResultMapper.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
@Override
public AnnotatedType getSubstituteType(AnnotatedType original) {
    AnnotatedType innerType = GenericTypeReflector.getTypeParameter(original, DataFetcherResult.class.getTypeParameters()[0]);
    return ClassUtils.addAnnotations(innerType, original.getAnnotations());
}
 
Example #13
Source File: DataFetcherResultMapper.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
@Override
public boolean supports(AnnotatedElement element, AnnotatedType type) {
    return ClassUtils.isSuperClass(DataFetcherResult.class, type);
}