简体   繁体   English

如何使用 java datafetcher 环境访问 graphql 查询中的请求标头?

[英]How can i access request headers in graphql query using java datafetcher environment?

I want to fetch a header value I am passing during a GraphQl Query call.我想获取在 GraphQl 查询调用期间传递的 header 值。 Something like we can do prior in case of rest api HttpServletRequest.getheader()在 rest api HttpServletRequest.getheader() 的情况下,我们可以事先做一些事情

I wanted to fetch it from the dataFetchingEnvironment but the context fetched from this value did not get me any means to fetch the header values from request.我想从 dataFetchingEnvironment 中获取它,但是从这个值中获取的上下文没有让我有任何方法从请求中获取 header 值。

        try {
            GraphQLContext context =  env.getGraphQlContext();
            String Id= context.getHeader("headerkeyIpass"); 
// I know this method does not exist i am trying to paint a picture as to what i am asking

I do not intend to change the resolver method calls but any inputs to improve my code would be great.我不打算更改解析器方法调用,但任何改进我的代码的输入都会很棒。

The GraphQLContext has method getHttpServletRequest() which returns GraphQLContext有方法getHttpServletRequest()返回

java.util.Optional<javax.servlet.http.HttpServletRequest> 

So from there u can get the headers所以从那里你可以得到标题

GraphQLContext context =  env.getGraphQlContext();
HttpServletRequest request = context.getHttpServletRequest().get();
String Id= request.getHeader("headerkeyIpass"); 

If you are using the latest graphql libraries there are some breaking changed and you can get the headers from GraphQLServletContext as shown here如果您使用的是最新的graphql 库,则有一些重大更改,您可以从GraphQLServletContext获取标头,如下所示

GraphQLServletContext graphQLServletContext = (GraphQLServletContext) env.getContext();
    
String user = graphQLServletContext.getHttpServletRequest().getHeader("user");

Like you said getHttpServletRequest does not exist on DataFetchingEnvironment.getGraphQlContext() when using the new official Spring 2.7 spring-boot-starter-graphql (not the legacy GraphQL Java Kickstart ones). Like you said getHttpServletRequest does not exist on DataFetchingEnvironment.getGraphQlContext() when using the new official Spring 2.7 spring-boot-starter-graphql (not the legacy GraphQL Java Kickstart ones).

Instead you can add an autowired HttpServletRequest request variable at the top of your controller and inside each query resolver it will be filled with the request context.相反,您可以在 controller 的顶部添加一个自动连接的HttpServletRequest请求变量,并且在每个查询解析器中,它将填充请求上下文。

@Controller
public class MyGraphQLController {
    ...

    @Autowired
    HttpServletRequest request;

    ...

    @QueryResolver(...)
    public XXX yyyy() {
        ...
        try {
            String Id= request.getHeader("headerkeyIpass"); 
        ...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM