【问题标题】:How to access the graphql query fired in the java program?如何访问在 java 程序中触发的 graphql 查询?
【发布时间】:2020-04-09 23:49:54
【问题描述】:

我正在使用 graphql 创建一个 rest api。我想在 java 程序中记录用户触发的查询。我无法访问程序中的查询。 以下是我写的一段代码:

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);
    }

}

这里我想在函数 create employee 中记录查询。 任何帮助将不胜感激。

【问题讨论】:

    标签: java spring graphql


    【解决方案1】:

    小提示:您不能使用 GraphQL 创建 REST API,因为它们是并发 API 模式。但这只是一个小提示(例如,请参阅 resource 以获得更好的理解)。

    解决您的问题:我不知道您使用的 GraphQL 库。也许有更好的可能性,但使用以下解决方案,无论库如何,您都应该能够实现您想要的。

    您始终可以通过 spring ben 或其他注入方法(取决于您的 Spring 版本)将请求对象检索为 javax.servlet.http.HttpServletRequest。有关注入示例,请参阅this question。

    示例:假设您使用 @Autowired 注释在您的类中注入 HttpServletRequest bean。 Spring 将在运行时注入适当的对象。然后您可以使用请求来获取请求的正文:

    @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);
    }
    

    【讨论】:

      猜你喜欢
      • 2019-01-02
      • 2011-02-15
      • 2017-02-09
      • 2016-08-23
      • 1970-01-01
      • 2018-11-06
      • 2018-06-15
      • 2022-09-26
      • 2018-08-01
      相关资源
      最近更新 更多