I'm using graphql-spqr-spring-boot-starter library to migrate the existing Rest API project to GraphQL. I have a below piece of code to fetch the current HttpServletRequest from RequestContextHolder for Rest API:

 HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
        .currentRequestAttributes()).getRequest();

However, this returns null for GraphQL. I believe that is correct because for GraphQL we have to use DefaultGlobalContext<ServletWebRequest> and not HttpServletRequest. But I'm not sure how can we do that.

But, I tried below piece of code:

RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
return (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST); 

But it didn't work - requestAttributes returns null.

I'm very new to GraphQL, could anyone please help me know how can I get HttpServletRequest (DefaultGlobalContext) for GraphQL? This will be much appreciated.

1

There are 1 best solutions below

0
On

It goes like this:

@GraphQLMutation
public void whateverMutation(@GraphQLRootContext DefaultGlobalContext<NativeWebRequest> ctx) {
    HttpServletRequest req = ctx.getNativeRequest().getNativeRequest(HttpServletRequest.class);
    HttpServletResponse res = ctx.getNativeRequest().getNativeResponse(HttpServletResponse.class);
    ...
}