GraphQL解析器返回列表最后一项的副本

时间:2018-11-07 12:01:02

标签: list graphql-js express-graphql

在Node.js程序中使用graphql-js包时,我看到了QueryRoot解析器,该解析器旨在返回自定义对象的列表,并返回包含所解析内容的最后一项的副本的列表。

const Person = new GraphQLObjectType({
  name: "Person",
  description: "This represents Person type",
  fields: () => ({
    favorite_game: { type: new GraphQLNonNull(GraphQLString) },
    favorite_movie: { type: new GraphQLNonNull(GraphQLString) }
  })
});

const QueryRootType = new GraphQLObjectType({
  name: "Schema",
  description: "Query Root",
  fields: () => ({
    persons: {
      type: new GraphQLNonNull(new GraphQLList(Person)),
      description: "List of persons",
      args: {
        input: {
          type: new GraphQLNonNull(Name)
        }
      },
      resolve: async (rootValue, input) => {
        return new Promise(function(resolve, reject) {
          getRESTPersonsByName(input, function(searchresults) {
            console.log(JSON.stringify(searchresults));
            resolve(searchresults);
          });
        });
      }
    }
  })
});

const Schema = new GraphQLSchema({
  query: QueryRootType
});

module.exports = Schema;

结果如下所示,其中显示了已解决的5个人列表中最后一个人的副本。我还在字段级别的解析器上验证了这一点,仍然看到同一个人进来。(解析器功能getRESTPersonsByName从底层API调用接收的结果很好,如预期的那样)

{
  data: 
  {
    persons : 
    [{
      "favorite_game" : "half life",
      "favorite_movie" : "life of pi"
     },
     {
      "favorite_game" : "half life",
      "favorite_movie" : "life of pi"
     },
     {
      "favorite_game" : "half life",
      "favorite_movie" : "life of pi"
     },
     {
      "favorite_game" : "half life",
      "favorite_movie" : "life of pi"
     },
     {
      "favorite_game" : "half life",
      "favorite_movie" : "life of pi"
    }]
  }
}

函数getRESTPersonsByName像这样-

function getRESTPersonsByName(input, callback) {
  let searchresults = [];
  let person1 = {favorite_game: "spider-man", favorite_movie: "spider-man"};
  let person2 = {favorite_game: "god of war", favorite_movie: "lord of the rings"};
  let person3 = {favorite_game: "forza horizon 4", favorite_movie: "fast and the furios"};
  let person4 = {favorite_game: "super mario", favorite_movie: "super mario bros"};
  let person5 = {favorite_game: "half life", favorite_movie: "life of pi"};
  searchresults.push(person1);
  searchresults.push(person2);
  searchresults.push(person3);
  searchresults.push(person4);
  searchresults.push(person5);
  console.log(JSON.stringify(searchresults));
  return callback(searchresults);
}

0 个答案:

没有答案