首页 > 解决方案 > 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);
}

标签: listgraphql-jsexpress-graphql

解决方案


推荐阅读