简体   繁体   中英

How to access the graphql query fired in the java program?

I am creating a rest api using graphql. I want to log the query fired by user in the java program. I cannot access the query in the program. Following is the piece of code I have written:

package com.x.demo.GraphQL.Resolver;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.coxautodev.graphql.tools.GraphQLMutationResolver;
import com.x.demo.GraphQL.Model.Employee;
import com.x.demo.GraphQL.Services.EmployeeService;

@Component
public class MutationResolver implements GraphQLMutationResolver{

    @Autowired
    private EmployeeService employeeService;

    public Employee createEmployee(String name, String profile, String DOJ, String salary) {
        return this.employeeService.createEmployee(name, profile, DOJ, salary);
    }

}

here I want to log the query in function create employee. Any help will be deeply appreciated.

Little hint: you cannot create a REST API with GraphQL because they're concurrent API patterns. But this is just a little hint (eg see this resource for a better understanding).

Coming to your problem: I don't know the GraphQL library you use. Maybe there is a better possibility but with the following solution you should be able to achieve what you want regardless the library.

You can always retrieve the request object as the javax.servlet.http.HttpServletRequest via spring been or other injection methods (depending on your Spring version). See this question for injection examples.

Example: Assuming you inject the HttpServletRequest bean in your class with the @Autowired Annotation. Spring will inject the proper object during runtime. You can then use the request to get the body of the request:

@Autowired
private HttpServletRequest request;

public Employee createEmployee(String name, String profile, String DOJ, String salary) {
        String body = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
        return this.employeeService.createEmployee(name, profile, DOJ, salary);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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