Graphql arguments returns {} when using variables - node.js

I just want to test my query mutation with Postman.
Here is my query
mutation ($input: registerSupplierInput){
registerSupplier(input: $input){
message
success
}
}
And variables:
{"email":"1#d.com", "name":"1", "address":"1", "location":[36.24,44.04], "phone_numbers":["1"]}
And here is my server schema types:
const registerSupplierInput = new GraphQLInputObjectType({
name: 'registerSupplierInput',
fields: {
name: {type: new GraphQLNonNull(GraphQLString)},
email: {type: new GraphQLNonNull(GraphQLString)},
address: {type: new GraphQLNonNull(GraphQLString)},
location: {type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(GraphQLFloat)))},
phone_numbers: {type: new GraphQLList(new GraphQLNonNull(GraphQLString))},
}
});
const registerSupplierResponse = new GraphQLObjectType({
name: 'registerSupplierType',
fields: {
success: {type: new GraphQLNonNull(GraphQLBoolean)},
message: {type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(GraphQLString)))},
}
});
module.exports.registerSupplier = {
type: new GraphQLNonNull(registerSupplierResponse),
args: {
input: {type: registerSupplierInput}
},
async resolve(_, args){
try {
console.log(_, args);
const {registerSupplier} = require('../controllers/supplier');
return await registerSupplier(args);
}
catch(error){
return error;
}
}
}
When i request a query the args parameter returns {} in the server log.
What's wrong with my code?

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 express nested schema

I am currently building mern + graphql app. I am new to graphql and I have two different models a User Model and Character model. The Character Model is nested in the User. When I create a user in the Graphiql interface I want it to display its data and the character that is associated with the specific user but instead it is displaying every character that has been created in the database and adding them to every user created instead of the specific user. Trying to figure out how to fix this. Link to Github Repo
Mongoose User Model
const mongoose = require('../db/connection')
const Schema = mongoose.Schema
const User = new Schema({
id: String,
name: String,
totalwins: Number,
description: String,
charactersID: [
{
type: Schema.Types.ObjectId,
ref: "Character"
}
]
})
module.exports = mongoose.model('User', User)
Mongoose Character Model
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const Character = new Schema({
name: String,
wins: Number,
losses: Number,
percentage: Number,
image: String
})
module.exports = mongoose.model('Character', Character)
const graphql = require('graphql')
const { GraphQLSchema, GraphQLObjectType, GraphQLString, GraphQLInt, GraphQLID, GraphQLList,
GraphQLNonNull } = graphql
const Character = require("../models/Character")
const User = require("../models/User")
Types
// User Schema
const userType = new GraphQLObjectType({
name: 'User',
fields : () => ({
_id: {type: GraphQLID},
name : { type: GraphQLString},
totalwins : { type: GraphQLInt },
description : { type: GraphQLString },
character : {
type : new GraphQLList(characterType),
resolve(parent, args){
return Character.find({charactersID: parent.id})
}
}
})
})
// Character Schema
const characterType = new GraphQLObjectType({
name: 'Character',
fields : () => ({
id: {type: GraphQLID},
name : { type: GraphQLString},
wins : { type: GraphQLInt },
losses : { type: GraphQLInt },
percentage: {type: (GraphQLInt)},
image: { type: GraphQLString },
})
})
Query
//query the graph to grab the data
const Query = new GraphQLObjectType({
name: 'Query',
fields: {
user : {
type: userType,
// arguments passed by the user while making the query
args: {id : {type : GraphQLID}},
resolve(parent, args){
// return User.find((item) => { return item.id == args.id});
//finding a single user by id
return User.findById(args.id)
}
},
users : {
type: new GraphQLList(userType),
resolve(parent, args) {
return User.find({})
}
},
character : {
type: characterType,
args: {id : {type : GraphQLID}},
resolve(parent, args){
return Character.findById(args.id)
}
},
characters : {
type: new GraphQLList(characterType),
resolve(parent, args) {
return Character.find({})
}
}
}
})
Mutations
//allows user to add, update and delete to mondodb through graphql
const Mutation = new GraphQLObjectType({
name: 'Mutation',
fields: {
addUser: {
type: userType,
args: {
name: {type: GraphQLNonNull(GraphQLString)},
totalwins: {type: (GraphQLInt)},
description: {type: (GraphQLString)},
charactersID: { type: new GraphQLNonNull(GraphQLID)}
},
resolve(parent, args){
let user = new User({
name: args.name,
totalwins: args.totalwins,
description: args.description,
charactersID: args.charactersID
})
return user.save()
}
},
addCharacter: {
type: characterType,
args: {
name: {type: GraphQLNonNull(GraphQLString)},
wins: {type: (GraphQLInt)},
losses: {type: (GraphQLInt)},
percentage: {type: (GraphQLInt)},
image: {type: (GraphQLString)},
},
resolve(parent, args){
let character = new Character({
name: args.name,
wins: args.wins,
losses: args.losses,
percentage: args.percentage,
image: args.image
})
return character.save()
}
},
deleteUser: {
type: userType,
args: {
id: {type: new GraphQLNonNull(GraphQLString)}
},
resolve(parent, args){
const remUser = User.findByIdAndRemove(args.id)
if(!remUser){
throw new Error('No character found')
}
return remUser
}
},
deleteCharacter: {
type: characterType,
args: {
id: {type: new GraphQLNonNull(GraphQLString)}
},
resolve(parent, args){
const remCharacter = Character.findByIdAndRemove(args.id)
if(!remCharacter){
throw new Error('No character found')
}
return remCharacter
}
},
}
})
module.exports = new GraphQLSchema({ query : Query, mutation : Mutation})
Image of results from Grapiql interface

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());
}
}
}
})
});

Promise block my reference on MongoDB/Node.js

I use Mongoose to MongoDb with Node.js/React/GraphQL.
I have a document Article who is related to another document Event who is related to several documents Tags. When I try to save my documents I always have a pending promise to into my tags in the Event document.
Result :
- Article is save related to Event
- Event is saved but not related to Tags
- Tags are saved but not related to Event
Expecting :
- Article is save related to Event
- Event is saved and related to Tags
- Tags are saved and related to Event
Two time, when my server was on the beginning is working without pending and error. So I think my problem is a time problem, but I don't know how to resolve it. I try to put some timeout but without success.
I have the following schema in Mongoose/MongoDb
//mode/event.js
'use strict';
//import dependency
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//create new instance of the mongoose.schema. the schema takes an object that shows
//the shape of your database entries.
var EventSchema = new Schema({
createdAt: {
type: Date,
default: Date.now
},
name: {
type: String,
required: 'Kindly enter the name of the event'
},
description: String,
site_web: String,
themes: {
type: String,
enum: ['Economics', 'Politics', 'Bitcoins', 'Sports'],
default: 'Economics'
},
picture: String,
event_date_start: Date,
event_date_end: Date,
type_event: {
type: String,
enum: ['Confrontation','Standard'],
default: 'Standard'
},
teams: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Team'
}],
tags: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Tag'
}]
});
//export our module to use in server.js
module.exports = mongoose.model('Event', EventSchema);
//model/tag.js
'use strict';
//import dependency
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//create new instance of the mongoose.schema. the schema takes an object that shows
//the shape of your database entries.
var TagSchema = new Schema({
name: {
type: String,
required: 'Kindly enter the name of the tag'
},
});
//export our module to use in server.js
module.exports = mongoose.model('Tag', TagSchema);
//model/article.js
'use strict';
//import dependency
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//create new instance of the mongoose.schema. the schema takes an object that shows
//the shape of your database entries.
var ArticleSchema = new Schema({
// _id: String,
createdAt: {
type: Date,
default: Date.now
},
event: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Event',
required: 'Kindly enter the event'
},
body: String,
type: {
type: String,
enum: ['Confrontation','Standard'],
default: 'Standard'
},
url_source: String,
themes: {
type: String,
enum: ['Economics', 'Politics', 'Bitcoins', 'Sports'],
default: 'Economics'
},
type_media: {
type: String,
enum: ['video', 'web', 'podcast'],
default: 'web'
},
article_date: Date,
});
//export our module to use in server.js
module.exports = mongoose.model('Article', ArticleSchema);
In my schema Node.js/GraphQL I have the resolve function
createArticle: {
type: ArticleType,
args: {
event: {type: EventCreateType},
body: {type: GraphQLString},
type: {type: articleType},
url_source: {type: GraphQLString},
themes: {type: themesType},
//type_media: {type: new GraphQLList(mediaType)}
type_media: {type: mediaType},
article_date : {type: GraphQLString}
},
resolve: async (source, params) => {
if (params.event) {
var eventparams = params.event;
var tagparams = params.event.tags;
params.event.tags = null;
params.event = null;
var tagIds = [];
//traitement des tags
var inEvent = await EventsModel.findOne({'name':eventparams.name});
if(!inEvent){
inEvent = new EventsModel(eventparams);
if(tagparams){
if(tagparams.length !=0){
tagIds = await tagparams.map(async function(c) {
var inTag = await TagsModel.findOne(c);
if(!inTag){
inTag = new TagsModel(c);
inTag.save(function(err) {
if (err) {
console.log(err);
}});
}
return inTag;
});
console.log('******************************Le tableau**************************');
console.dir(tagIds);
console.log('********************************************************');
//inEvent.tags = tagIds;
Promise.all(tagIds).then(function(savedObjects) {
console.log('********************************************************');
console.log('Le Inside Tab:',savedObjects);
console.log('********************************************************');
// Do something to celebrate?
inEvent.tags = savedObjects;
}).catch(function(err) {
// one or both errored
console.log(err);
});
}
}
inEvent.save(function(err) {
if (err) {
console.log(err);
}});
}
console.log('*******************propriete inEvent*****************************');
console.dir(inEvent);
console.log('********************************************************');
var articleModel = new ArticlesModel(params);
articleModel.event = inEvent;
console.log('***********************propriete Article before save****************');
console.dir(articleModel);
console.log('********************************************************');
articleModel.save(function(err, article) {
if (err) {
console.log(err);
}
if (article) {
return ArticlesModel.findById(article._id)
.populate('article')
.populate('event')
.exec(function(error, articles) {
console.log('article saved: succes')
articles.article.articles.push(articles);
articles.article.save(function(err, article) {
if (err) {
console.log(err);
}
});
return articles;
})
}
});
return articleModel;
}
else{
console.log('verif 3');
}
console.log('verif 4');
}
},

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