While using graphql-js package in my Node.js program, I see the QueryRoot resolver that's meant to return a list of custom objects, returns a list with copies of last item of what it resolves.
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;
The result is like below, which shows copies of the last person in the list of 5 persons resolved. I also verified this at the field level resolver, still seeing same person coming in. (The resolver function getRESTPersonsByName is receiving the results fine from underlying API call, as expected)
{
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"
}]
}
}
Function getRESTPersonsByName goes something like this -
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);
}