javascript – GraphQL Error with Sequelize

Question:

I have an error returning a Mutation . Apparently it can't read the id field, but the object I send to GraphQL has this field, and as I'm new to GraphQL I don't understand what the error means.

The mistake:

{
  "errors": [
    {
      "message": "Cannot return null for non-nullable field UserVoucher.id.",
      "locations": [
        {
          "line": 48,
          "column": 5
        }
      ],
      "path": [
        "createUserVoucher",
        "id"
      ]
    }
  ],
  "data": {
    "createUserVoucher": null
  }
}

The mutation is where I insert the bank (it correctly inserts the element):

createUserVoucher: (parent, args, { user, models }) => {
  args['userId'] = user.id;
  models.UserVoucher.count({
    where: {utilized: true, pinId: args.pinId, userId: args.userId}
  }).then( c => {
    if (c > 0) {
      return []
    } else {
      models.Voucher.findOne({
        where: {
          id: args.voucherId
        }
      }).then( voucher => {
        models.UserVoucher.count({
          where: { voucherId: args.voucherId }
        }).then( c => {
          if (c < voucher.captured) {
            if (user.name, user.gender, user.username, user.email, user.phoneNumber, user.city, user.state, user.cpf) {
              return models.UserVoucher.create(args) //RETORNA AQUI
            }
          }
        })
      })
    }
  });
  return []
}

The UserVoucher definition:

type UserVoucher {
  id: Int!
  nodeId: Int!
  userId: ID!
  voucherId: ID!
  voucher: Voucher
  pinId: ID!
  capturedAt: DateTime
  utilized: Boolean
}
`;

The definition of mutation:

createUserVoucher(
  pinId: Int!, 
  voucherId: Int!
): UserVoucher

Any ideas what I can do to solve this or at least a light to debug better?

Answer:

After asking the OS in English, I realized that the error was in Promises and not GraphQL.

createUserVoucher: async (parent, args, { user, models }) => {
  args['userId'] = user.id;
  const c = await models.UserVoucher.count({
    where: {utilized: true, pinId: args.pinId, userId: args.userId}
  })
  if (c > 0) return null
  const voucher = await models.Voucher.findOne({
    where: { id: args.voucherId }
  })
  const c2 = await models.UserVoucher.count({ 
    where: { voucherId: args.voucherId }
  })
  return models.UserVoucher.create(args) // still need a return here
}

Furthermore, a refactoring using Async Await was suggested which greatly improved code readability.

Scroll to Top