首页 文章

如何以GraphQL模式语言返回嵌套对象

提问于
浏览
3

我正在阅读GraphQl的文档,并意识到新的Schema Langugage仅支持默认的解析器 . 有没有办法在使用新的架构语言时添加自定义解析器?

let userObj = {
  id: 1,
  name: "A",
  homeAddress: {
    line1: "Line1",
    line2: "Line2",
    city: "City"
  }
};

let schema = buildSchema(`
  type Query {
    user(id: ID): User
  }

  type User {
    id: ID
    name: String
    address: String 
  }
`);

//I would like User.address to be resolved from the fields in the json response eg. address = Line1, Line2, City

这是我定义的架构 . 我想在这里添加一些行为,这将允许我解析地址对象并返回连接的字符串值 .

2 回答

  • 2

    正如HagaiCo所提到的那样,正确的方法是graphql-tools .

    它有一个名为makeExecutableSchema的函数,它接受一个模式并解析函数,然后返回一个可执行模式

  • 0

    看起来你在这里有一个混乱,因为你定义了该地址是String但你发送一个字典来解决它 .

    您可以做的是定义标量地址类型: scalar AddressType 如果您使用buildSchema然后将解析函数附加到它 . (或使用graphql-tools轻松完成)

    或者从头开始构建类型,如the official documentations所示:

    var OddType = new GraphQLScalarType({
      name: 'Odd',
      serialize: oddValue,
      parseValue: oddValue,
      parseLiteral(ast) {
        if (ast.kind === Kind.INT) {
          return oddValue(parseInt(ast.value, 10));
        }
        return null;
      }
    });
    
    function oddValue(value) {
      return value % 2 === 1 ? value : null;
    }
    

    然后你可以将字典解析为字符串(parseValue),否则

相关问题