Prisma atomic operations on update fails on undefined

Viewed 22

So the prisma typescript definition for atomic operations says:

export type IntFieldUpdateOperationsInput = {
  set?: number
  increment?: number
  decrement?: number
  multiply?: number
  divide?: number
}

The Prisma Schema:

model SomeEntity {
  id           Int     @id @default(autoincrement())
  quantity     Int
}

So we have a variable that could be a number or undefined

const someQuantity:number|undefined = undefined

And we wanted to update the quantity field with this variable like so:

const client = new PrismaClient();
client.someEntity.update({ where: { id: 1 }, data:{ quantity:{ increment: someQuantity }}})

If someQuantity===undefined prisma throws an Error: [ERROR] 09:47:48 Error: Invalid `prisma.someEntity.update()` invocation:

for the undefined value, but the type signature tells me that this should be valid. we are using the prisma version 2.28.0 and a postgres db. Is there some configuration that I'm missing or is it just a bug that has to be reported.

1 Answers

You must check that typeof someQuantity === "number" before your perform the increment operation. The TypeScript type you provided explains it all:

export type IntFieldUpdateOperationsInput = {
  set?: number
  increment?: number
  decrement?: number
  multiply?: number
  divide?: number
}

In your case, the increment variable can have a type of either undefined or number. If the variable is not undefined, it must be undefined.

In your situation, if the increment operation is the ONLY thing that you are doing, Prisma will fail if there's nothing else going on in the operation. The full error you get from Invalid 'prisma.someEntity.update()' invocation should be pretty descriptive as to WHY the operation is failing.

In order to solve this error, you can't perform your update operation UNLESS increment is a number.

if (typeof someQuantity !== "number") {
  return;
}

// At this point, `someQuantity` MUST be a number
const client = new PrismaClient();
client.someEntity.update({
    where: {
        id: 1
    },
    data: {
        quantity: {
            increment: someQuantity
        }
    }
})
Related