Graphql mutation returning null, but database is updated

515 views javascript
8

I'm trying to add a mutation to allow for the client to add a document to the LineItem schema. The code I've written below allows me to do that when I test it using GraphiQL, but the response I get is null. How do I fix the code so that the response is the new document?

addLineItem: {
    type: LineItemType,
    args: {
      orderId: {type: new GraphQLNonNull(GraphQLID)},
      productId: {type: new GraphQLNonNull(GraphQLID)},
      quantity: {type: new GraphQLNonNull(GraphQLInt)}
    },
    resolve(parent, args) {
      Product.findById(args.productId, (err, result) => {
        let price = result.price;
        let subtotal = price*args.quantity;
        let lineitem = new LineItem({
          orderId : args.orderId,
          productId : args.productId,
          quantity : args.quantity,
          subtotal: subtotal
        });
        return lineitem.save();
    }}
  }
},

answered question

2 Answers

7

Actually there is nothing wrong with your code . .

You need to specify a return value as a type (e.g. Boolean, String, etc). Types can be nullable, for example: the value can be null, and, in fact, they are nullable by default unless you define them with !

so there is nothing wrong with null return value.

posted this
4

The problem is that you are not returning any value in resolve function, the lineitem.save(); returns the value inside the callBack

make resolve function async, remove the findById callBack and await for the result, then implement your logic and return the value, like below:

async resolve(parent, args) {
  const result = await Product.findById(args.productId);

  let price = result.price;
  let subtotal = price*args.quantity;
  let lineitem = new LineItem({
    orderId : args.orderId,
    productId : args.productId,
    quantity : args.quantity,
    subtotal: subtotal
  });

  return lineitem.save();
}

posted this

Have an answer?

JD

Please login first before posting an answer.