我们可以通过graphql提供ExecutionResult接口的自定义实现,以自定义输出吗?

时间:2019-03-26 14:41:05

标签: graphql graphql-java

我必须自定义graphql(默认为json)提供的输出,以将其更改为例如。 csv或任何其他格式。 有没有办法为ExecutionResult提供自定义实现,例如ExecutionResultImpl,并提供一种类似于Specification()的方法,以便在将映射返回到graphql之前修改映射并将其转换为所需的输出?

我想知道是否有办法解决这个问题?

任何帮助将不胜感激! 谢谢

当我尝试实现它时,由于返回类型为实例ExecutionResultImpl,因此它会在运行时返回ClassCastException。

这是我尝试过的自定义实现:




import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import graphql.ExecutionResult;
import graphql.GraphQLError;

public class ExecutionResultCustomImpl implements ExecutionResult {

    private final Object data;
    private final List<GraphQLError> errors;
    private final transient boolean dataPresent;
    private final transient Map<Object, Object> extensions;

    public ExecutionResultCustomImpl(boolean dataPresent, Object data, List<? extends GraphQLError> errors, Map<Object, Object> extensions) {
        this.dataPresent = dataPresent;
        this.data = data;

        if (errors != null && !errors.isEmpty()) {
            this.errors = Collections.unmodifiableList(new ArrayList<>(errors));
        } else {
            this.errors = Collections.emptyList();
        }

        this.extensions = extensions;
    }

    public boolean isDataPresent() {
        return dataPresent;
    }

    @Override
    public <T> T getData() {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public List<GraphQLError> getErrors() {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public Map<Object, Object> getExtensions() {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public Map<String, Object> toSpecification() {
        // TODO Auto-generated method stub
        return null;
    }

     public Map<String, Object> toCsvSpecification() {
            Map<String, Object> result = new LinkedHashMap<>();
            if (dataPresent) {
                File file = new File("data.csv");
                result.put("data", data);
                System.out.println("***********"+file.getAbsolutePath());
            }
            if (errors != null && !errors.isEmpty()) {
                //result.put("errors", errorsToSpec(errors));
                File file = new File("errors.csv");
                System.out.println("***********"+file.getAbsolutePath());
            }
            if (extensions != null) {
                result.put("extensions", extensions);
                File file = new File("extensions.csv");
                System.out.println("***********"+file.getAbsolutePath());
            }
            return result;
        }


}

0 个答案:

没有答案