1
votes

Hello I am new to graphql and I was wondering if it is possible to create a root query in my schema that will return an array or list as a result.

To be more precise I have created the following type in my schema:

const ResourceType = new GraphQLObjectType({
  name:'Resource',
  fields:()=>({
   id: {type: GraphQLID},
   url: {type: GraphQLString},
   title: {type: GraphQLString},
   author: {type: GraphQLString},
   license:{type: GraphQLString},
   LicenseScore: {type: GraphQLFloat},
 })
});

And I want to query all the resources in my database so that I get their license type and then assign a score according to the license. Is it possible to have a query that gets the license for each resource and returns an array like this: [[id:1209,score:3.5],[1203,4.5]....]?

I have created a mutation that updates the score to the database, here it is:

updateAllLicenses: {
     type: new GraphQLList(ResourceType),
     async resolve(parent,args){
     var licns;
     var scr;
     await Resource.find({}).then(async function(results){
       var num = results.length;
       var scr=0;
       for (var i=0; i<num; i++){
         if (! (results[i].license in licenseScores)){
           scr = 0;
         }
         else{
           scr = licenseScores[results[i].license];
         }
         await Resource.findByIdAndUpdate(results[i].id{LicenseScore:scr});
        }
      });
      return await Resource.find({});
    }
   }

However I was wondering if there is a way to get these scores directly from the query instead of saving them in the database. I tried changing the type to new GraphQLList(GraphQLFloat) and returning an array with the scr values but I get an error in the graphql api saying I have the wrong output type in my mutation.

1
Are you sure of the syntax of your wanted result: ` [[id:1209,score:3.5],[1203,4.5]....]?? Or should you meant [[id:1209,score:3.5],[id:1203,score:4.5]....]?`Anas Tiour
No I meant [[1209,3.5],[1203,4.5]] I only wrote the id and score to show the order in which I wish to save the values. Is it possible to get an array as a result from a query? if so what type should the return value have?gzarnomitrouhotmailcom

1 Answers

0
votes

From your schema, it seems to me that you are able to fetch results, as an array of objects, with an output like this:

[
    {
        id: 1,
        license: "value1"
    },
    {
        id: 2,
        license: "value2"
    }
]

If this is all you need, then the approximate query should work:

query Resource {
    id
    url
    license
    licenseScore
}

Once you have your array of objects, you can convert it to an array of arrays, although I would not advise that.

Since you are just getting started in GraphQL, I recommened these resources:

  • HowToGraphql: clean videos/posts on GraphQL
  • Apollo Graphql's documentation and blogs. Here is one of the posts on queries

Also, if you want to test your queries and get accustomed to them, use GraphQL Playground