Passing array as argument in GraphQL - node.js

I have started working on GraphQL.My schema contains one list item too.
Following is the code of my schema:
var userType = new graphql.GraphQLObjectType({
name: 'user',
fields: function () {
return {
_id: {
type: graphql.GraphQLID
},
name: {
type: graphql.GraphQLString
},
age: {
type: graphql.GraphQLString
},
degrees:[
{type:graphql.GraphQLList}
]
}
}
});
AND the query is as follows:
var QueryType = new graphql.GraphQLObjectType({
name: 'Query',
fields: () => ({
userArr: {
type: new graphql.GraphQLList(userType),
args:{
degrees:{type:new graphql.GraphQLList(userType)}
},
resolve: function(source, args) {
console.log(args);
resolve(args);
}
}
})
})
I got this error.
Basically i need to post the array from client graphql query and have to define query accordingly which i am unable to achieve.
Any suggestions because i can't find any help over this issue..

GraphQLObjectType is not a valid input type.
See Mutations and Input Types
"Input types can't have fields that are other objects, only basic scalar types, list types, and other input types."
You can use the suggestion above because GraphQLString is a scalar
degrees:{
type:new graphql.GraphQLList(graphql.GraphQLString)
}
Otherwise, you would need to define a GraphQLInputObjectType
const userInputType = new GraphQLInputObjectType({
name: 'userInput',
fields: { /* put your fields here */ }
});
/* some code in between */
degrees:{
type:new graphql.GraphQLList(userInputType)
}

I did something very similar recently. Your input arguments don't need to hold to the same type system as the when it's formatting the output data to send back. So your arg just needs to simply accept a list of strings or objects, or whatever standard type you want to send in.
In this case, I updated it to accept a list(array) of strings.
var QueryType = new graphql.GraphQLObjectType({
name: 'Query',
fields: () => ({
userArr: {
type: new graphql.GraphQLList(userType),
args:{
degrees:{type:new graphql.GraphQLList(graphql.GraphQLString)}
},
resolve: function(source, args) {
console.log(args);
resolve(args);
}
}
})
})
Also, I noticed on your user type, you have degrees surrounded with array brackets.
Similar to your degrees input argument, you'll be outputting an array of strings.
Try something like this:
degrees:{
type:new graphql.GraphQLList(graphql.GraphQLString)
}
Happy coding!

Related

Expected Iterable, but did not find one for field \"Query.customers\ [duplicate]

I'm currently trying GraphQL with NodeJS and I don't know, why this error occurs with the following query:
{
library{
name,
user {
name
email
}
}
}
I am not sure if the type of my resolveLibrary is right, because at any example I had a look at they used new GraphQL.GraphQLList(), but in my case I really want to return a single user object, not an array of users.
My code:
const GraphQL = require('graphql');
const DB = require('../database/db');
const user = require('./user').type;
const library = new GraphQL.GraphQLObjectType({
name: 'library',
description: `This represents a user's library`,
fields: () => {
return {
name: {
type: GraphQL.GraphQLString,
resolve(library) {
return library.name;
}
},
user: {
type: user,
resolve(library) {
console.log(library.user);
return library.user
}
}
}
}
});
const resolveLibrary = {
type: library,
resolve(root) {
return {
name: 'My fancy library',
user: {
name: 'User name',
email: {
email: 'test#123.de'
}
}
}
}
}
module.exports = resolveLibrary;
Error:
Error: Expected Iterable, but did not find one for field library.user.
So my library schema provides a user field which returns the right data (the console.log is called).
I ran into this problem as well. It appears that what you're returning from your resolver doesn't match the return type in your schema.
Specifically for the error message Expected Iterable, but did not find one for field library.user., your schema expects an array(Iterable) but you aren't returning an array in your resolver
I had this in my schema.js:
login(email: String, password: String): [SuccessfulLogin]
I changed that to:
login(email: String, password: String): SuccessfulLogin
Notice the square brackets around "SuccessfulLogin". It's up to you whether you want to update the resolver return type or update the schema's expectations
I guess your user is an instance of GraphQLList that is why the field user is expecting to resolve to an iterable object.
I had the same problem. I was using find instead filter.
I ran into the same issue but i was using GraphQL with Go.
Solution:
I mentioned the return type to be a list( or you can say an array), but my resolver function was returning an interface and not a list of interfaces.
Before it was =>
Type: graphql.NewList(graphqll.UniversalType)
Later i changed it to =>
Type: graphqll.UniversalType
graphqll.UniversalType : 'graphqll' is the name of my user-defined package and 'UniversalType' is the GraphQL object i have created.
The previous structure of graphql object was :
var GetAllEmpDet = &graphql.Field{
Type: graphql.NewList(graphqll.UniversalType),
Resolve: func(params graphql.ResolveParams) (interface{}, error) {
...
...
// Your resolver code goes here, how you handle.
...
return models.Universal, nil // models.Universal is struct and not list of struct so it gave that error.
},
}
It worked when i changed this to:
var GetAllEmpDet = &graphql.Field{
Type: graphqll.UniversalType,
Resolve: func(params graphql.ResolveParams) (interface{}, error) {
...
...
// Your resolver code goes here, how you handle.
...
return models.Universal, nil // models.Universal is struct and not list of struct so it gave that error.
},
}
It's usually a simple mistake. Caused by declaring in the schema a List instead of a Field. The reverse will happen if you interchange. An example from Django-graphene. Switch from this:
my_query_name = graphene.List(MyModelType, id=graphene.Int())
to this:
my_query_name = graphene.Field(MyModelType, id=graphene.Int())
In my case it was related to django-graphene I didn't have a resolve method defined.
class SomeNode(DjangoObjectType):
things = graphene.List(ThingNode)
def resolve_things(self, info, **kwargs):
return self.things.all()
For me, it was a simple fix.
items: {
type: new GraphQLList(VideoType),<-- error
resolve(parentValue, args) {
const url = 'www'
return axios.get(url)
.then(res => res.data);
}
}
and change it to
items: {
type: VideoType,
resolve(parentValue, args) {
const url = 'www'
return axios.get(url)
.then(res => res.data);
}
}
I faced the same issue. For me, it was an issue with Mongo DB model.js file.
GraphQL kept throwing that error because my model was saving the field as an object whereas graphQL was returning it as an array.
The code that caused the error was this.
tableHeaders: {
text: {
type: String,
required: false,
},
align: {
type: String,
required: false,
},
sortable: {
type: Boolean,
required: false,
},
value: {
type: String,
required: false,
},
},
It was corrected to the following.
tableHeaders: [
{
text: {
type: String,
required: false,
},
align: {
type: String,
required: false,
},
sortable: {
type: Boolean,
required: false,
},
value: {
type: String,
required: false,
},
},
],
Changing type from object to array fixed it.
i had the same issue i was using findOne and that seems like the issue that didnt worked. i changed to find and it worked
#Query(()=> [Post])
async getSinglePost(
#Arg('post_id') id: string,
){
/*
const post = await getConnection().getRepository(Post).findOne({uuid:postuid})
console.log(post);
return post
*/
const post = Post.find({uuid:id})
return post
}
This simply results due to the import error
earlier code
const books =require('./data')
// Resolvers define the technique for fetching the types defined in the
// schema. This resolver retrieves books from the "books" array above.
const resolvers = {
Query: {
books(){
return books;
},
},
}
module.exports = { resolvers };
just replace the import statement with
const {books} =require('./data')
as you had ex

Rolling back resolve function from GraphQLObjectType to another

I'm currently studying GraphQL and as part of the developing process, i'm interested with modularization of my code - i do understand how to write query, but fail to understand how to correctly implement query of queries.
That is the rootQuery.js
const {
GraphQLInt,
GraphQLList,
GraphQLObjectType,
GraphQLSchema,
GraphQLFloat,
GraphQLString
} = require("graphql");
const bankRootQuery = require('../graphql/queries/bank.queries')
const rootQuery = new GraphQLObjectType({
name: "rootQuery",
fields: {
bankRootQuery: { type: bankRootQuery, resolve: () => { console.log(bankRootQuery.resolve) } }
}
});
module.exports = new GraphQLSchema({
query: rootQuery
});
And here is the bankRootQuery.js:
const { GraphQLObjectType, GraphQLInt, GraphQLNonNull, GraphQLID, GraphQLList } = require("graphql");
const BankType = require('../types/bank.type');
const models = require('../../models/models_handler');
module.exports = new GraphQLObjectType({
name: "bankRootQuery",
fields: {
getbanks: {
type: new GraphQLList(BankType),
resolve: () => {
return models.getBanks()
}
},
getbankByID: {
type: BankType,
args: {
bankID: { name: "bankID", type: GraphQLInt }
},
resolve: (_, args) => {
if (!models.getBanks().has(args.bankID))
throw new Error(`Bank with ID ${args.bankID} doesn't exists`);
return models.getBank(args.bankID);}
}
}
});
Assining bankRootQuery to the scheme object instead of rootQuery works perfectly fine, but using the rootQuery yields with null result when querying using GraphiQL - The Documentation Explorer structure seems to be in proper manner, so i'm guessing the problem is with the resolve function, which i don't understand how to define correctly.
Here is the result when querying using GraphQL:
{
"data": {
"bankRootQuery": null
}
}
If a field resolves to null, then execution for that "branch" of the graph ends. Even if the field's type is an object type, none of the resolvers for its "children" fields will be called. Imagine if you had a field like user -- if the field resolves to null, then it makes no sense to try to resolve the user's name or email.
Your resolver for the bankRootQuery field just logs to the console. Because it doesn't have a return statement, its return value is undefined. A value of undefined is coerced into a null. Since the field resolved to null, execution halts.
If you want to return something other than null, then your resolver needs to return something -- even if it's just an empty object ({}). Then the resolvers for any "child" fields will work as expected.
In general, I would advise against nesting your queries like this -- just keep them at the root level. For additional details around how field resolution works, check out this post.

Express GraphQL schema error when requesting from a public API [duplicate]

I'm currently trying GraphQL with NodeJS and I don't know, why this error occurs with the following query:
{
library{
name,
user {
name
email
}
}
}
I am not sure if the type of my resolveLibrary is right, because at any example I had a look at they used new GraphQL.GraphQLList(), but in my case I really want to return a single user object, not an array of users.
My code:
const GraphQL = require('graphql');
const DB = require('../database/db');
const user = require('./user').type;
const library = new GraphQL.GraphQLObjectType({
name: 'library',
description: `This represents a user's library`,
fields: () => {
return {
name: {
type: GraphQL.GraphQLString,
resolve(library) {
return library.name;
}
},
user: {
type: user,
resolve(library) {
console.log(library.user);
return library.user
}
}
}
}
});
const resolveLibrary = {
type: library,
resolve(root) {
return {
name: 'My fancy library',
user: {
name: 'User name',
email: {
email: 'test#123.de'
}
}
}
}
}
module.exports = resolveLibrary;
Error:
Error: Expected Iterable, but did not find one for field library.user.
So my library schema provides a user field which returns the right data (the console.log is called).
I ran into this problem as well. It appears that what you're returning from your resolver doesn't match the return type in your schema.
Specifically for the error message Expected Iterable, but did not find one for field library.user., your schema expects an array(Iterable) but you aren't returning an array in your resolver
I had this in my schema.js:
login(email: String, password: String): [SuccessfulLogin]
I changed that to:
login(email: String, password: String): SuccessfulLogin
Notice the square brackets around "SuccessfulLogin". It's up to you whether you want to update the resolver return type or update the schema's expectations
I guess your user is an instance of GraphQLList that is why the field user is expecting to resolve to an iterable object.
I had the same problem. I was using find instead filter.
I ran into the same issue but i was using GraphQL with Go.
Solution:
I mentioned the return type to be a list( or you can say an array), but my resolver function was returning an interface and not a list of interfaces.
Before it was =>
Type: graphql.NewList(graphqll.UniversalType)
Later i changed it to =>
Type: graphqll.UniversalType
graphqll.UniversalType : 'graphqll' is the name of my user-defined package and 'UniversalType' is the GraphQL object i have created.
The previous structure of graphql object was :
var GetAllEmpDet = &graphql.Field{
Type: graphql.NewList(graphqll.UniversalType),
Resolve: func(params graphql.ResolveParams) (interface{}, error) {
...
...
// Your resolver code goes here, how you handle.
...
return models.Universal, nil // models.Universal is struct and not list of struct so it gave that error.
},
}
It worked when i changed this to:
var GetAllEmpDet = &graphql.Field{
Type: graphqll.UniversalType,
Resolve: func(params graphql.ResolveParams) (interface{}, error) {
...
...
// Your resolver code goes here, how you handle.
...
return models.Universal, nil // models.Universal is struct and not list of struct so it gave that error.
},
}
It's usually a simple mistake. Caused by declaring in the schema a List instead of a Field. The reverse will happen if you interchange. An example from Django-graphene. Switch from this:
my_query_name = graphene.List(MyModelType, id=graphene.Int())
to this:
my_query_name = graphene.Field(MyModelType, id=graphene.Int())
In my case it was related to django-graphene I didn't have a resolve method defined.
class SomeNode(DjangoObjectType):
things = graphene.List(ThingNode)
def resolve_things(self, info, **kwargs):
return self.things.all()
For me, it was a simple fix.
items: {
type: new GraphQLList(VideoType),<-- error
resolve(parentValue, args) {
const url = 'www'
return axios.get(url)
.then(res => res.data);
}
}
and change it to
items: {
type: VideoType,
resolve(parentValue, args) {
const url = 'www'
return axios.get(url)
.then(res => res.data);
}
}
I faced the same issue. For me, it was an issue with Mongo DB model.js file.
GraphQL kept throwing that error because my model was saving the field as an object whereas graphQL was returning it as an array.
The code that caused the error was this.
tableHeaders: {
text: {
type: String,
required: false,
},
align: {
type: String,
required: false,
},
sortable: {
type: Boolean,
required: false,
},
value: {
type: String,
required: false,
},
},
It was corrected to the following.
tableHeaders: [
{
text: {
type: String,
required: false,
},
align: {
type: String,
required: false,
},
sortable: {
type: Boolean,
required: false,
},
value: {
type: String,
required: false,
},
},
],
Changing type from object to array fixed it.
i had the same issue i was using findOne and that seems like the issue that didnt worked. i changed to find and it worked
#Query(()=> [Post])
async getSinglePost(
#Arg('post_id') id: string,
){
/*
const post = await getConnection().getRepository(Post).findOne({uuid:postuid})
console.log(post);
return post
*/
const post = Post.find({uuid:id})
return post
}
This simply results due to the import error
earlier code
const books =require('./data')
// Resolvers define the technique for fetching the types defined in the
// schema. This resolver retrieves books from the "books" array above.
const resolvers = {
Query: {
books(){
return books;
},
},
}
module.exports = { resolvers };
just replace the import statement with
const {books} =require('./data')
as you had ex

GraphQL.js circular dependency - "Field type must be Output Type but got: undefined."

I have been banging my head against this problem for hours. I have a very simple GraphQL implementation in Node.js as follows.
const UserType = new GraphQLObjectType({
name: 'User',
fields: () => ({
id: new GraphQLNonNull(GraphQLString),
username: new GraphQLNonNull(GraphQLString)
})
});
const QueryType = new GraphQLObjectType({
name: 'QueryType',
fields: () => {
user: {
type: UserType,
args: { id: { name: 'id', type: new GraphQLNonNull(GraphQLString) } },
resolve: (parent, args) => getUser(args.id)
}
})
});
const schema = new GraphQLSchema({
query: QueryType,
});
It works if the "type" of the "user" field of QueryType is anything else (for example, GraphQLString). If it's UserType, however, I get the following error.
"Error: User.id field type must be Output Type but got: undefined."
The stack trace doesn't point anywhere useful, just leads into the GraphQL module itself. This shouldn't be a circular dependency problem as far as I can tell, though I tried thunking it just in case. Any help would be greatly appreciated, because this is driving me nuts.

GraphQL Expected Iterable, but did not find one for field xxx.yyy

I'm currently trying GraphQL with NodeJS and I don't know, why this error occurs with the following query:
{
library{
name,
user {
name
email
}
}
}
I am not sure if the type of my resolveLibrary is right, because at any example I had a look at they used new GraphQL.GraphQLList(), but in my case I really want to return a single user object, not an array of users.
My code:
const GraphQL = require('graphql');
const DB = require('../database/db');
const user = require('./user').type;
const library = new GraphQL.GraphQLObjectType({
name: 'library',
description: `This represents a user's library`,
fields: () => {
return {
name: {
type: GraphQL.GraphQLString,
resolve(library) {
return library.name;
}
},
user: {
type: user,
resolve(library) {
console.log(library.user);
return library.user
}
}
}
}
});
const resolveLibrary = {
type: library,
resolve(root) {
return {
name: 'My fancy library',
user: {
name: 'User name',
email: {
email: 'test#123.de'
}
}
}
}
}
module.exports = resolveLibrary;
Error:
Error: Expected Iterable, but did not find one for field library.user.
So my library schema provides a user field which returns the right data (the console.log is called).
I ran into this problem as well. It appears that what you're returning from your resolver doesn't match the return type in your schema.
Specifically for the error message Expected Iterable, but did not find one for field library.user., your schema expects an array(Iterable) but you aren't returning an array in your resolver
I had this in my schema.js:
login(email: String, password: String): [SuccessfulLogin]
I changed that to:
login(email: String, password: String): SuccessfulLogin
Notice the square brackets around "SuccessfulLogin". It's up to you whether you want to update the resolver return type or update the schema's expectations
I guess your user is an instance of GraphQLList that is why the field user is expecting to resolve to an iterable object.
I had the same problem. I was using find instead filter.
I ran into the same issue but i was using GraphQL with Go.
Solution:
I mentioned the return type to be a list( or you can say an array), but my resolver function was returning an interface and not a list of interfaces.
Before it was =>
Type: graphql.NewList(graphqll.UniversalType)
Later i changed it to =>
Type: graphqll.UniversalType
graphqll.UniversalType : 'graphqll' is the name of my user-defined package and 'UniversalType' is the GraphQL object i have created.
The previous structure of graphql object was :
var GetAllEmpDet = &graphql.Field{
Type: graphql.NewList(graphqll.UniversalType),
Resolve: func(params graphql.ResolveParams) (interface{}, error) {
...
...
// Your resolver code goes here, how you handle.
...
return models.Universal, nil // models.Universal is struct and not list of struct so it gave that error.
},
}
It worked when i changed this to:
var GetAllEmpDet = &graphql.Field{
Type: graphqll.UniversalType,
Resolve: func(params graphql.ResolveParams) (interface{}, error) {
...
...
// Your resolver code goes here, how you handle.
...
return models.Universal, nil // models.Universal is struct and not list of struct so it gave that error.
},
}
It's usually a simple mistake. Caused by declaring in the schema a List instead of a Field. The reverse will happen if you interchange. An example from Django-graphene. Switch from this:
my_query_name = graphene.List(MyModelType, id=graphene.Int())
to this:
my_query_name = graphene.Field(MyModelType, id=graphene.Int())
In my case it was related to django-graphene I didn't have a resolve method defined.
class SomeNode(DjangoObjectType):
things = graphene.List(ThingNode)
def resolve_things(self, info, **kwargs):
return self.things.all()
For me, it was a simple fix.
items: {
type: new GraphQLList(VideoType),<-- error
resolve(parentValue, args) {
const url = 'www'
return axios.get(url)
.then(res => res.data);
}
}
and change it to
items: {
type: VideoType,
resolve(parentValue, args) {
const url = 'www'
return axios.get(url)
.then(res => res.data);
}
}
I faced the same issue. For me, it was an issue with Mongo DB model.js file.
GraphQL kept throwing that error because my model was saving the field as an object whereas graphQL was returning it as an array.
The code that caused the error was this.
tableHeaders: {
text: {
type: String,
required: false,
},
align: {
type: String,
required: false,
},
sortable: {
type: Boolean,
required: false,
},
value: {
type: String,
required: false,
},
},
It was corrected to the following.
tableHeaders: [
{
text: {
type: String,
required: false,
},
align: {
type: String,
required: false,
},
sortable: {
type: Boolean,
required: false,
},
value: {
type: String,
required: false,
},
},
],
Changing type from object to array fixed it.
i had the same issue i was using findOne and that seems like the issue that didnt worked. i changed to find and it worked
#Query(()=> [Post])
async getSinglePost(
#Arg('post_id') id: string,
){
/*
const post = await getConnection().getRepository(Post).findOne({uuid:postuid})
console.log(post);
return post
*/
const post = Post.find({uuid:id})
return post
}
This simply results due to the import error
earlier code
const books =require('./data')
// Resolvers define the technique for fetching the types defined in the
// schema. This resolver retrieves books from the "books" array above.
const resolvers = {
Query: {
books(){
return books;
},
},
}
module.exports = { resolvers };
just replace the import statement with
const {books} =require('./data')
as you had ex

Resources