【问题标题】:Change backend service based on GraphQL Param基于 GraphQL Param 更改后端服务
【发布时间】:2020-02-29 13:40:48
【问题描述】:

我有一个这样的 GraphQL Schema:

BigParent (parentParam: Boolean) {
  id
  name
  Parent {
    id
    name
    Child (childParam: Boolean) {
      id
      name
    }
  }
}

如何编写解析器,以便我根据 parentParamtrue 还是 childParamtrue 来调用不同的后端 API?第一个选项是直截了当的。第二个需要根据Child级别返回的服务数据返回的值来重构Graph。

我不认为这两个选项都是真的,因为我会分配一些优先级,以便在传递父级别的参数时不考虑子级别的参数。

【问题讨论】:

    标签: graphql apollo apollo-server


    【解决方案1】:

    您可以通过遍历 GraphQL 解析器 info 参数来获取查询中任何字段选择的参数。

    假设您的查询如下所示:

    query {
      BigParent(parentParam: Boolean) {
        id
        name
        Parent {
          id
          name
          Child(childParam: Boolean) {
            id
            name
          }
        }
      }
    }
    

    你应该可以做这样的事情:

    function getChildParam(info) {
      // TODO: Return 'childParam'
    }
    
    const resolvers = {
      Query: {
        async BigParent(parent, args, context, info) {
          // 'args' contains the 'parentParam' argument
          const parentParam = args.parentParam;
    
          // Extract the 'childParam' argument from the info object
          const childParam = getChildParam(info);
    
          if (parentParam || childParam) {
            return context.datasource1.getData();
          }
    
          return context.datasource2.getData();
        },
      },
    };
    

    【讨论】:

      猜你喜欢
      • 2021-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-01
      • 1970-01-01
      • 2019-12-22
      • 1970-01-01
      • 2011-08-12
      相关资源
      最近更新 更多