2

I am trying to make crud application using graphql. But I am not sure about update request. I tried, but it's not working. Here see my code. Create post and query posts are working fine.

I am using express and express-graphql. I tried going through docs but. I am unable to figure out.

schema

const graphqlHttp = require('express-graphql');
const {buildSchema} = require('graphql');

app.use('/graphql', graphqlHttp({
schema: buildSchema(`
        type Post {
            _id: ID!
            title: String!
            description: String!
            content: String!
            date: String!
        }
        input PostInput {
            title: String!
            description: String!
            content: String!
            date: String!
        }
        type RootMutation {
            createPost(postInput: PostInput!): Post
            updatePost(_id: ID!, postInput: PostInput!): Post

        }
        schema{
            query: RootQuery
            mutation: RootMutation
        }       
    `),

resolver

updatePost: args => {   
            console.log(args); <!-- this log gives nothing 
            Post.findByIdAndUpdate(args._id, {$set: {
                title: args.postInput.title,
                description: args.postInput.description,
                content: args.postInput.content,
                date: new Date(args.postInput.date)
            }})
                .then(result => {
                    console.log(result);
                    return {
                        ...result._doc
                    }        
                }).catch (err =>{
                    throw err;
            });
        },

localhost:8080/graphql making mutation

mutation {
  updatePost(_id: "5d5a3f380930813c647cb697", postInput: {title: "update title", description: "update", content: "update content", date: "2019-08-19T06:18:06.778Z"}) {
    title
  }
}

mutation result

{
  "data": {
    "updatePost": null
  }
}
aditya kumar
  • 2,905
  • 10
  • 39
  • 79
  • you probably not passing values to your `updatePost` methog, show how its called – Medet Tleukabiluly Aug 19 '19 at 07:18
  • @MedetTleukabiluly show what ?? I am not getting. – aditya kumar Aug 19 '19 at 07:26
  • where do you call `updatePost`? – Medet Tleukabiluly Aug 19 '19 at 09:16
  • Usually in mutation, first argument is root item, second is incoming data, third is context. `updatePost: (root, args, ctx) => { args is your data }` – Medet Tleukabiluly Aug 19 '19 at 10:31
  • do you get any data on your "console.log(result)"? If so, can you share the data structure? – Marco Daniel Aug 19 '19 at 12:22
  • @MarcoDaniel no I didn't get any data in `console.log(result)`. – aditya kumar Aug 20 '19 at 04:01
  • @MedetTleukabiluly the function will only receive three parameters (args, context, info) when it's passed through the root object, which is the only way to try to customize field resolution when working with `buildSchema`. Which is also why [you shouldn't be using buildSchema](https://stackoverflow.com/questions/53984094/notable-differences-between-buildschema-and-graphqlschema/53987189#53987189). – Daniel Rearden Aug 21 '19 at 12:18
  • @adityakumar I'm guessing you're not seeing *anything* logged, as opposed to seeing `undefined` or `null`, which would indicate the function is not being called in the first place. Please update your question to include the complete configuration object you're passing to `express-graphql`. You will need to at least put a return in front of `Post.findByIdAndUpdate`, but if the function isn't being called at all, the problem lies outside of the function itself. – Daniel Rearden Aug 21 '19 at 12:27
  • @DanielRearden I did update my question have a look. Anyway if buildSchema is not a good option. can please suggest me some other options available, I am new to graphql I don't know much about it. – aditya kumar Aug 21 '19 at 13:35
  • did u check database if it is updated. if it is then convert promise to async/await – Yilmaz Aug 31 '19 at 23:44

2 Answers2

3

Wrong arguments:

I'm used to Apollo, because of its simplified structure. In Apollo I've encountered a similar issue whereas the arguments of queries and mutations in the resolver consist of 4 different items.

updatePost: (parent,args,context,info) => {   // <-- look at this line
            console.log(args);
            Post.findByIdAndUpdate(args._id, {$set: {
                title: args.postInput.title,
                description: args.postInput.description,
                content: args.postInput.content,
                date: new Date(args.postInput.date)
            }}).then(result => {
                    console.log(result);
                    return {
                        ...result._doc
                    }        
                }).catch (err =>{
                    throw err;
            });
        },
ExampleMutation2: ...

Bonus ECMA:

I would also recommend to use the await/async version of the resolver method in order to get a response and not a Promise. Read https://www.greycampus.com/blog/programming/java-script-versions in order to make your code simpler using the latest ECMAScript

   updatePost: async (parent,args,context,info) => {
                try{
                  console.log(args);
                  let result= await Post.findByIdAndUpdate(args._id, {$set: {
                      title: args.postInput.title,
                      description: args.postInput.description,
                      content: args.postInput.content,
                      date: new Date(args.postInput.date)
                  }})
                  console.log(result);
                  return result._doc
                }catch (err =>{
                  throw err;
                });
            },
    ExampleMutation2: ...
Andrea
  • 1,286
  • 6
  • 18
  • in addition to this, return `result.toObject()` instead of `result._doc`. All `_names` are ideally supposed to be private. – itaintme Aug 27 '19 at 10:51
0

I know that i am late an you probably fixed it but it might help someone else.

type RootMutation {
            updatePost(_id: ID!, postInput: PostInput!): Post

instead write:

updatePost(id: ID!, postInput: PostInput!): Post!
No name
  • 13
  • 4