GraphQL Query.resolve must be an object - node.js

I'm new to GraphQL and trying to get a basic query setup against a mock data source that just resolves a promise with a filter to pull the record by id. I have the following:
const {
GraphQLSchema,
GraphQLObjectType,
GraphQLString,
GraphQLList
} = require('graphql')
const db = require('../db')
const getUserById = (id) => db.read(id)
const UserType = new GraphQLObjectType({
name: 'User',
description: 'User Type',
fields: () => ({
first_name: {
type: GraphQLString
},
last_name: {
type: GraphQLString
},
email: {
type: GraphQLString
},
friends: {
type: new GraphQLList(UserType),
resolve: (user) => user.friends.map(getUserById)
}
})
})
const QueryType = new GraphQLObjectType({
name: 'Query',
description: 'User Query',
fields: () => ({
user: {
type: UserType,
args: {
id: { type: GraphQLString }
}
},
resolve: (root, args) => getUserById(args.id)
})
})
const schema = new GraphQLSchema({
query: QueryType
})
module.exports = schema
When I try to run this with graphQLHTTP I get the following:
Error: Query.resolve field config must be an object
I've been following Zero to GraphQL in 30 Minutes and can't figure out what I'm doing wrong.

You've accidentally made the resolver for the user query one of the fields on the Query type. Move it inside the user field and you should be good.

Related

I have this error Unauthorised admin to execute command mongoose + Graphql

I used mongoose and Graphql to send my queries to the database but for some reason it doesn't let me create documents. I have tried creating a new user with full admin privileges it hasn't worked I tried changing the default user password but it didn't work.
I rechecked my mongoose model no errors so what might be the problem.
FYI the problem arose with the return (author.save()) and the database connects normally
Author Model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const authorSchema = new Schema({
name: String,
age: Number
});
module.exports = mongoose.model('Author', authorSchema);
schema.js
const graphql = require('graphql');
const Book = require('../models/book');
const Author = require('../models/Author');
const _ = require('lodash');
const {
GraphQLObjectType,
GraphQLString,
GraphQLSchema,
GraphQLID,
GraphQLInt,
GraphQLList
} = graphql;
const BookType = new GraphQLObjectType({
name: 'Book',
fields: ( ) => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
genre: { type: GraphQLString },
author: {
type: AuthorType,
resolve(parent, args){
//return _.find(authors, { id: parent.authorId });
}
}
})
});
const AuthorType = new GraphQLObjectType({
name: 'Author',
fields: ( ) => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
age: { type: GraphQLInt },
books: {
type: new GraphQLList(BookType),
resolve(parent, args){
//return _.filter(books, { authorId: parent.id });
}
}
})
});
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
book: {
type: BookType,
args: { id: { type: GraphQLID } },
resolve(parent, args){
//return _.find(books, { id: args.id });
}
},
author: {
type: AuthorType,
args: { id: { type: GraphQLID } },
resolve(parent, args){
//return _.find(authors, { id: args.id });
}
},
books: {
type: new GraphQLList(BookType),
resolve(parent, args){
//return books;
}
},
authors: {
type: new GraphQLList(AuthorType),
resolve(parent, args){
//return authors;
}
}
}
});
const Mutation = new GraphQLObjectType({
name: 'Mutation',
fields: {
addAuthor: {
type: AuthorType,
args: {
name: { type: GraphQLString },
age: { type: GraphQLInt }
},
resolve(parent, args){
let author = new Author({
name: args.name,
age: args.age
});
return (author.save())
}
}
}
});
module.exports = new GraphQLSchema({
query: RootQuery,
mutation: Mutation
})
;
error message
(node:31482) MongoError: (Unauthorized) not authorized on admin to execute command {
insert: "authors", documents: [[{name gyfdgyiszukjfheusdzyih} {age 88} {_id
ObjectID("60af9c682215ea7afad86f4c")} {__v 0}]], ordered: false, writeConcern: { w:
"majority" }
Found this issue, after trying practice by GraphQL tutorial on Youtube.
To solve it, you need to update your mongoose model to the last version.

Graphql always returns null

I'm trying to get data from a mongodb collection using graphql and mongoose but graphql always resolves to null. This is the query I am trying:
getUser(email: "john#gmail.com"){
name
}
const userModel = new Mongoose.model("db.users", {
_id: String,
email: String,
name: String
});
const userType = new GraphQLObjectType({
name: "user",
fields : {
_id: {type: GraphQLID},
email: {type: GraphQLString},
name: {type: GraphQLString}
}
});
// Construct a schema
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name:"query",
fields: {
getUser: {
type: userType,
args: {
email: {
type: GraphQLString,
}
},
resolve: async(root, args, context, info) => {
return await(userModel.findOne(args).exec());
}
}
}
})
});

Graphql execute where condition only if the argument is passed

I am using graphql in node js for my oracle database wherein I connect to the remote database and fetch some details. I am fairly new to these technologies so please pardon me. I have a customer table with below schema:
const Customer = new GraphQLObjectType({
description: 'Customer data schema',
name: 'Customer',
fields: () => ({
name: {
type: GraphQLString,
sqlColumn: 'NAME',
},
city: {
type: GraphQLString,
sqlColumn: 'CITY'
},
country: {
type: GraphQLString,
sqlColumn: 'COUNTRY'
},
gender: {
type: GraphQLString,
sqlColumn: 'GENDER'
},
emp_id: {
type: GraphQLString,
sqlColumn: 'EMP_ID'
}
})
});
Customer._typeConfig = {
sqlTable: 'CUSTOMER',
uniqueKey: ['NAME','EMP_ID']
}
Using join monster I create my Query root as:
const QueryRoot = new GraphQLObjectType({
description: 'global query object',
name: 'RootQuery',
fields: () => ({
customer: {
type: new GraphQLList(Customer),
args: {
emp_id: {
description: 'Emp Id',
type: GraphQLString
},
name: {
description: 'Customer Name',
type: GraphQLString
}
},
where: (customer, args, context) => {
return `${customer}."EMP_ID" = :emp_id AND ${customer}."NAME" = :name`;
},
resolve: (parent, args, context, resolveInfo) => {
return joinMonster(resolveInfo, context, sql => {
console.log('joinMaster', sql);
return database.simpleExecute(sql, args,{
outFormat: database.OBJECT
});
});
}
}
})
})
When I pass my query in graphql in browser with emp_id and name parameters I get data. But there are cases when I cannot pass any parameters and would want all the rows to be fetched.
When I do not send the parameters I get error as:
ORA-01008 : Not all variables bound
I want the arguments to be optional, and if I don't send them then it should return all rows.
Thank you.
Both the where and resolver functions are passed an args argument. This will have the parameter names and values if any. You can use that argument to build a dynamic where clause. Here's an untested example:
const QueryRoot = new GraphQLObjectType({
description: 'global query object',
name: 'RootQuery',
fields: () => ({
customer: {
type: new GraphQLList(Customer),
args: {
emp_id: {
description: 'Emp Id',
type: GraphQLString
},
name: {
description: 'Customer Name',
type: GraphQLString
}
},
where: (customer, args, context) => {
if (Object.keys(args).length === 0) {
return false;
}
let whereClause = '1 = 1';
if (args.emp_id != undefined) {
whereClause += `\n AND ${customer}."EMP_ID" = :emp_id`;
}
if (args.name != undefined) {
whereClause += `\n AND ${customer}."NAME" = :name`;
}
return whereClause;
},
resolve: (parent, args, context, resolveInfo) => {
return joinMonster(resolveInfo, context, sql => {
console.log('joinMaster', sql);
return database.simpleExecute(sql, args,{
outFormat: database.OBJECT
});
});
}
}
})
})
Since the where clause would then match the number of arguments, you shouldn't get the ORA-01008 error.

graph Ql schema using graphQlObjectType

i am beginner in Graph Ql.but i am trying to create a grapghql server with node and express as follow...
const graphql = require('graphql');
const _ = require('lodash')
const { GraphQlObjectType, GraphQLString,GraphQLSchema,buildSchema } =
graphql;
var books=[
{name:'Hezaro yek Shab',gener:'romans',id:1},
{name:'Fergosen memorizes',gener:'sport',id:2},
{name:'Hpliday physics',gener:'sience',id:3}
];
const BookType = new GraphQlObjectType({
name: 'Book',
fields: () => ({
id: { type: GraphQLString },
title: { type: GraphQLString },
gener: { type: GraphQLString }
})
});
const RootQuery=new GraphQlObjectType({
name:'RootQueryType',
fields:{
book:{
type:BookType,
args:{ id: { type: GraphQLString }},
resolve(parent,args){
return _.find(books,{id:args.id});
}
}
},
});
module.exports=new GraphQLSchema({
query:RootQuery
});
i used GraphQlObjectType to create schema for book and for Root Query and then passed book type into Root Query type as well .
any way i want to find particular book in array of books (data dont come from database at this time -just from local array)
but i have this error
The GraphQlObjectType is not a constructor error because of a typo, change it to GraphQLObjectType.

GraphQL Schema.js File Error - Node/express

I am using node, express, mongoose, and graphql.
I'm getting this error in the graphql console:
"message": "The type of SocialPostInQue.socialPost must be Output Type but got: undefined.\n\nThe type of SocialPostInQue.schedule must be Output Type but got: undefined.\n\nThe type of Mutation.addSocialPostInQue(socialPost:) must be Input Type but got: undefined.\n\nThe type of Mutation.addSocialPostInQue(schedule:) must be Input Type but got: undefined." I think the error my be origionating in the Type in the Schema.js File.
I do not know where undefined is coming from because I haven't run a query or mutation. Do you see any issues in my code?
My SocialPostInQue schema file is:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const SocialPostInQueSchema = new Schema({
userId: String,
socialPost: {
id: String,
message: String,
image: {
url: String
}
},
schedule: {
month: String,
date: Number,
hour: String,
minute: String
}
});
module.exports = mongoose.model('SocialPostInQue', SocialPostInQueSchema);
And my Schema.js file is:
const axios = require('axios');
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const {
GraphQLObjectType,
GraphQLString,
GraphQLInt,
GraphQLID,
GraphQLSchema,
GraphQLList,
GraphQLNonNull
} = require('graphql');
/****** Mongoose Schemas ******/
const SOCIALPOSTINQUE = require('./socialPostInQue');
/******* Types POSSIBLE ORIGIN*******/
const SocialPostInQueType = new GraphQLObjectType({
name:'SocialPostInQue',
fields:() => ({
id: {type:GraphQLID},
userId: {type:GraphQLID},
socialPost: {
id: {type:GraphQLID},
message: {type:GraphQLString},
image: {
url: {type:GraphQLString}
}
},
schedule: {
month: {type:GraphQLString},
date: {type:GraphQLInt},
hour: {type:GraphQLString},
minute: {type:GraphQLString}
}
})
});
/****** functions ******/
const socialPostInQueList = () => {
return new Promise((resolve, reject) => {
SOCIALPOSTINQUE.find((err, socialPostsInQue) => {
if (err) reject(err)
else resolve(socialPostsInQue)
})
})
};
/****** Root Query WHERE 'SocialPostInQue.socialPost OUTPUT UNDEFINED ERROR IS******/
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
socialPostInQue: {
type: SocialPostInQueType,
args: {
id: {type:GraphQLID}
},
resolve (parentValue, {id}) {
return SOCIALPOSTINQUE.findById(id)
}
},
socialPostsInQue:{
type: new GraphQLList (SocialPostInQueType),
resolve (parentValue, args) {
return socialPostInQueList()
}
}
}
})
/***** Root Mutations WHERE 'Mutation.addSocialPostInQue...' ERRORS COME FROM*******/
const mutation = new GraphQLObjectType({
name:'Mutation',
fields:{
addSocialPostInQue:{
type: SocialPostInQueType,
args:{
userId: {type: new GraphQLNonNull (GraphQLID)},
socialPost: {
id: {type: new GraphQLNonNull (GraphQLID)},
message: {type: new GraphQLNonNull (GraphQLString)},
image: {
url: {type: new GraphQLNonNull (GraphQLString)}
}
},
schedule: {
month: {type: new GraphQLNonNull (GraphQLString)},
date: {type: new GraphQLNonNull (GraphQLInt)},
hour: {type: new GraphQLNonNull (GraphQLString)},
minute: {type: new GraphQLNonNull (GraphQLString)}
}
},
resolve(parentValue, args){
console.log('READ', args)
let newSocialPostInQue = new SOCIALPOSTINQUE({
name: args.name,
email: args.email,
age: args.age,
userId: args.userId,
socialPost: {
id: args.socialPost.id,
message: args.socialPost.message,
image: {
url: args.socialPost.image.url
}
},
schedule: {
month: args.schedule.month,
date: args.schedule.date,
hour: args.schedule.hour,
minute: args.schedule.minute
}
});
return new Promise((resolve, reject) => {
newSocialPostInQue.save(function (err) {
if(err) reject(err)
else resolve(newSocialPostInQue)
})
console.log ("New Social Post In Que Added")
});
}
}
}
})
module.exports = new GraphQLSchema({
query: RootQuery,
mutation
});
All nested non-scalar types need to be constructed as object types. Note the socialPost, image and schedule fields:
const SocialPostInQueType = new GraphQLObjectType({
name:'SocialPostInQue',
fields:() => ({
id: {type:GraphQLID},
userId: {type:GraphQLID},
socialPost: new GraphQLObjectType({
name: 'SocialPostType',
fields: {
id: {type:GraphQLID},
message: {type:GraphQLString},
image: new GraphQLObjectType({
name: 'ImageType',
fields: {
url: {type:GraphQLString}
}
})
}
}),
schedule: new GraphQLObjectType({
name: 'SocialPostSchedule',
fields: {
month: {type:GraphQLString},
date: {type:GraphQLInt},
hour: {type:GraphQLString},
minute: {type:GraphQLString}
}
})
})
})

Resources