java - 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 中做到这一点?我似乎找不到任何明确的答案。
解决方案
有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();
推荐阅读
- php - php7.4 opcache.preload - fpm 启动错误
- reactjs - Axios 的 2 个 API 调用,都显示在本地服务器中 - 但只有一个显示已部署
- firebase - 测试 Firestore 时的单元测试超时
- html - nuxt.js 如何在页面中包含“.html”后缀?
- python - 为检查用户是否被列入黑名单的视图创建自定义装饰器
- sql - SQL - 使用两列向实体添加约束
- swift - 如何在进入区域后的某个时间安排推送通知?迅速
- javascript - 无法更改材质 UI 选择组件的填充
- c# - 如何在 C# 中将字符串转换为 HTTP 响应?
- swift - 此代码中 .enumerated() 和 .map() 的目的是什么?