Home > Blockchain >  Invalid prisma type error on nested writes
Invalid prisma type error on nested writes

Time:12-10

Hi I'm building an API with prisma and I have a type error when creating a new object with nested writes.

Here is my schema definition

    // This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["extendedWhereUnique", "interactiveTransactions"]
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model User {
  id        Int       @id @default(autoincrement())
  email     String    @unique
  password  String
  createdAt DateTime  @default(now())
  updatedAt DateTime  @updatedAt()
  Address   Address[]
  Review    Review[]
  Payment   Payment[]

  @@map("users")
}

model Token {
  id        Int      @id @default(autoincrement())
  token     String
  isValid   Boolean  @default(true)
  createdAt DateTime @default(now())

  @@map("tokens")
}

model Address {
  id        Int      @id @default(autoincrement())
  user      User?    @relation(fields: [userId], references: [id])
  userId    Int?
  city      String
  country   String
  type      String
  zipCode   String
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt()

  @@map("addresses")
}

model Category {
  id        Int       @id @default(autoincrement())
  name      String
  createdAt DateTime  @default(now())
  updatedAt DateTime  @updatedAt()
  Product   Product[]

  @@map("categories")
}

model Product {
  id          Int        @id @default(autoincrement())
  name        String
  description String?
  price       Int        @default(0)
  quantity    Int        @default(0)
  category    Category?  @relation(fields: [categoryId], references: [id])
  categoryId  Int?
  isAvailable Boolean
  createdAt   DateTime   @default(now())
  updatedAt   DateTime   @updatedAt()
  reviews     Review[]
  CartItem    CartItem[]

  @@map("products")
}

model Review {
  id        Int      @id @default(autoincrement())
  product   Product  @relation(fields: [productId], references: [id])
  productId Int
  mark      Int
  comment   String?
  user      User?    @relation(fields: [userId], references: [id])
  userId    Int?
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt()

  @@map("reviews")
}

model CartItem {
  id         Int      @id @default(autoincrement())
  cart       Cart     @relation(fields: [cartId], references: [id])
  cartId     Int
  product    Product  @relation(fields: [productId], references: [id])
  productId  Int
  quantity   Int      @default(0)
  unitPrice  Int      @default(0)
  totalPrice Int      @default(0)
  createdAt  DateTime @default(now())

  @@map("cart-items")
}

model Cart {
  id        Int        @id @default(autoincrement())
  createdAt DateTime   @default(now())
  CartItem  CartItem[]
  Payment   Payment[]

  @@map("carts")
}

model Payment {
  id        Int      @id @default(autoincrement())
  user      User?    @relation(fields: [userId], references: [id])
  userId    Int?
  cart      Cart     @relation(fields: [cartId], references: [id])
  cartId    Int
  email     String
  price     Int      @default(0)
  createdAt DateTime @default(now())

  @@map("payments")
}

When I'm trying to create a new payment with a userId it say that my type number is not assignable to undefined.

Here is my controller where I'm trying to use it

export async function createPayment(
  req: Request,
  res: Response
): Promise<ApiResponse> {
  try {
    const paymentProducts = await getPaymentProducts(req.body.products);
    const totalPrice = paymentProducts.reduce(
      (prev, curr) => prev   curr.price,
      0
    );
    const payment = await prisma.payment.create({
      data: {
        userId: req.user.id, // error here
        price: totalPrice,
        email: req.user.email,
        cart: {
          create: {
            CartItem: {
              create: paymentProducts.map((product) => ({
                productId: product.id,
                quantity: product.quantity,
                unitPrice: product.price,
                totalPrice: product.price * product.quantity,
              })),
            },
          },
        },
      },
    });
    return res.status(201).json(payment);
  } catch (e) {
    logger.error(JSON.stringify(e, null, 4));
    return res.status(500).json({ error: "Unexpected error occurred" });
  }
}

I don't know why it says that there is an error on userId. I precise that I correctly extend the express request to add the user and on other controller it work perfectly

CodePudding user response:

instead

 userId: req.user.id,

try

 userId: {
   connect: {
      id: req.user.id, // potentially parseInt here
   },
 },

this is required because you have relation between payment and user.

you can read more here:

https://www.prisma.io/docs/concepts/components/prisma-client/relation-queries#connect-an-existing-record

  • Related