1

I was doing some Prisma requests and I noticed that some Promises weren't working.

I know I could use async-await, but this should work.

prisma
  .user({ uid })
  .then(user => {
    if (Object.keys(user).length) throw 'error!'

    return prisma.updateUser({
      data: { money: user.money - 50 },
      where: { id: user.id }
    })
  })
  .then(user => {
    prisma
      .createLog({
        user: { connect: { id: user.id } },
        type: 'TICKET_BOUGHT',
        date: new Date()
      })
      .then(() => console.log('Ticket bought'))
  })
  .catch(error => console.error(error))

If the user doesn't exist, it should throw an error, but instead the second 'then' is run.

JuanM04
  • 27
  • 2
  • 8

2 Answers2

1

Try this:

 if (!Object.keys(user).length) throw 'error!'
EugenSunic
  • 13,162
  • 13
  • 64
  • 86
0

if (Object.keys(user).length) throw 'error!' that's mean if user exists, because object.keys function will return array list of object keys .length checking array length,

so if user exists ? Object.keys will return array list of user properties, that's mean length will be greater than zero and if condition will be true so throw will run,

If user not exist Object.keys will return zero and if(0) equal false so the throw will not run

In your case you should check if( ! Object.keys(user).length ) or if( Object.keys(user).length === 0 ) or you can check if( !user || user == {} ) or if( !user || !user.uid) instead of uid you can change it to any required property and you are sure 100% this property will return in all cases

Yasser Mas
  • 1,652
  • 1
  • 10
  • 14