首页 > 解决方案 > graphql-java-servlet 对 SimpleGraphQLServlet 的移除

问题描述

在旧版本的 graphql-java-servlet 中,我曾经扩展 SimpleGraphQLServlet,然后覆盖 GraphQLContext createContext( Optional request, Optional response ) 以将 cookie 添加到响应中。我还将覆盖 GraphQLErrorHandler getGraphQLErrorHandler() 以进行一些自定义错误处理。

我现在正在尝试对 graphql-java-servlet 6.x 的版本进行大幅提升。从 graphql-java-servlet 6.x 开始,SimpleGraphQLServlet 消失了。现在有一个 SimpleGraphQLHttpServlet,我不能直接使用。

不幸的是,github 文档已经过时了,即使它早已不复存在,仍然建议使用 SimpleGraphQLServlet。有一些构建器,我可以在 github 文档之外找到一些非常简单的参考资料,但它们都没有涵盖我的用例。

我不想做任何花哨的事情,但我需要能够将 cookie 添加到响应中并进行一些自定义错误处理。

如何在 graphql-java-servlet 6.x 中做到这一点?我似乎找不到任何明确的答案。

标签: javagraphqlgraphql-java

解决方案


GraphQLServletListener。它也在项目文档中进行了描述,尽管它有点错误(OperationCallback代码中没有)。

无论如何,这是一段工作代码(使用com.graphql-java-kickstart:graphql-java-servlet:6.1.4):

    GraphQLSchema schema = getSchema();
    List<GraphQLServletListener> listeners = new ArrayList<GraphQLServletListener>();
    GraphQLServletListener lstnr = new GraphQLServletListener(){

        public RequestCallback onRequest(HttpServletRequest request, HttpServletResponse response) {
            System.out.println("onRequest:" + request.getRequestURI());
            //TODO cookies here
            response.addCookie(new Cookie("sample","test"));

            return new RequestCallback() {

                @Override
                public void onSuccess(HttpServletRequest request, HttpServletResponse response) {
                    System.out.println("onSuccess:" + request.getRequestURI());
                }

                @Override
                public void onError(HttpServletRequest request, HttpServletResponse response, Throwable throwable) {
                    //TODO add some error handling here
                    System.out.println("onError:" + request.getRequestURI());
                }

                @Override
                public void onFinally(HttpServletRequest request, HttpServletResponse response) {
                    System.out.println("onFinally:" + request.getRequestURI());
                }

            };
        }
    };
    listeners.add(lstnr);

    SimpleGraphQLHttpServlet servlet = SimpleGraphQLHttpServlet.newBuilder(schema)
        .withListeners(listeners)
        .build();

推荐阅读