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

com.spring.boxes.dollar.support.graphql.instrument.NestInstrumentationContext Maven / Gradle / Ivy

The newest version!
package com.spring.boxes.dollar.support.graphql.instrument;

import java.util.concurrent.CompletableFuture;

import com.spring.boxes.dollar.support.graphql.GraphqlPaths;
import graphql.ExecutionResult;
import graphql.execution.instrumentation.InstrumentationContext;
import graphql.execution.instrumentation.parameters.InstrumentationFieldCompleteParameters;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class NestInstrumentationContext implements InstrumentationContext {

    private final InstrumentationFieldCompleteParameters parameters;

    private NestInstrumentationContext(InstrumentationFieldCompleteParameters parameters) {
        this.parameters = parameters;
    }

    public static NestInstrumentationContext context(InstrumentationFieldCompleteParameters parameters) {
        return new NestInstrumentationContext(parameters);
    }

    @Override
    public void onDispatched(CompletableFuture future) {

    }

    @Override
    public void onCompleted(ExecutionResult result, Throwable ex) {
        NestInstrumentationState state = parameters.getInstrumentationState();
        String nowFieldPath = GraphqlPaths.getNowFieldPath(parameters.getExecutionStepInfo().getPath());
        NestFutureTask futureTask = GraphqlPaths.getPathAdjoinFuture(state, nowFieldPath);
        if (futureTask == null) {
            return;
        }
        // graphql sec: https://spec.graphql.org/draft/#sec-Combining-List-and-Non-Null
        if (futureTask.getFuture().isCompletedExceptionally()) {
            if (ex != null) {
                futureTask.getFuture().whenComplete((ignore, existEx) -> {
                    existEx.addSuppressed(ex);
                });
            }
            return;
        }

        if (ex != null) {
            futureTask.getFuture().completeExceptionally(ex);
            return;
        }

        if (result.getData() != null) {
            if (GraphqlPaths.isInListPath(futureTask)) {
                futureTask.getTempResult().add(result.getData());
            } else {
                futureTask.getFuture().complete(result.getData());
                GraphqlPaths.completeSubTask(futureTask);
            }
        } else {
            // 对于没有结果的情况、仍然抛出异常,来终止程序运行
            // 这里是否需要让调度器感知异常信息?不需要,包含在结果中了
            futureTask.getFuture().completeExceptionally(new Throwable("empty result for " + nowFieldPath));
        }
    }


}