Graphql error with Sequelize

Asked

Viewed 63 times

3

I have an error in the return of a Mutation. Apparently he 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
  }
}

A Mutation and where I insert into 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 definition of Uservoucher:

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 idea what I can do to fix this or at least a light to debug better?

1 answer

0


After asking in the OS in English, I realized that the error was in Promises and not in 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
}

In addition it was suggested a refactoring using Async Await which greatly improved the reading of the code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.