Thanabhas
Thanabhas

Reputation: 67

Is there a more concise way to write this? (Need to connect relation upon creation in Prisma)

model Case{
  id String @id @default(uuid())
  caseId Int @unique @default(autoincrement())
  title String
  status Status[]

}


model Status{
  id String @id @default(uuid())
  statusId Int @unique @default(autoincrement())
  title String
  caseId Int
  story Story[]
  case Case? @relation(fields: [caseId],references: [caseId], onDelete: Cascade)
}

So let's say I have two Prisma Models like this. Case is the bigger one, so that one can be created with just the title. Now, I want it so that for someone to create a status, it needs to come with the caseId. So the post body is like this

{
  "caseId": 1,
  "title": "string"
}

As such, right now my create code is like this

async create(status: CreateStatusDto) {
    const {caseId, ... rest} = status
    if(!caseId){
      throw new BadRequestException('Please Input Case Id')
    }
    return await this.prismaService.status.create({
      data: {
        ...rest,
        case: {
          connect: {
            caseId: caseId
          }
        }
      }
    })
  }

And it's not exactly pretty, so I'm looking for a better way to write it. Any suggestions?

Upvotes: 1

Views: 64

Answers (1)

Lucas
Lucas

Reputation: 661

First of all, you could use a ValidationPipe to check if caseId is valid.

Second, you might wanna take a look at Exception Filters as they would make your code cleaner and your life easier (your exception should inform what happened, and not "ask" for the user to fix it, as you're doing).

As for Prisma, here's an example from Prisma's doc on nested writes:

const createUserAndPost = await prisma.user.create({
  data: {
    email: '[email protected]',
    name: 'Elsa Prisma',
    posts: {
      create: [
        { title: 'How to make an omelette' },
        { title: 'How to eat an omelette' },
      ],
    },
  },
})

Upvotes: 1

Related Questions