简体   繁体   中英

Nestjs/Prisma Rest API - GET [Related field]

I am building my first (non-tutorial) Rest API with Nestjs and Prisma. It is intended to be a simple simulacrum of an inventory management system. It currently has a very simple structure and models items in boxes on shelves. Each of these is represented by a table in a Postgres DB with the following schema and relations (I have only included shelves and boxes for brevity):

model Shelf {
  id     String  @id @default(uuid()) 
  boxes  Box[]
}

model Box {
  id     String  @id @default(uuid())
  shelf Shelf @relation(fields:[shelfId], references:[id])
  shelfId String
  items Item[]
}

I can create, fetch, filter and delete successfully, but my problem is trying to fetch an array of all the boxes on a specific shelf, and subsequently all items in a specific box.

I have gone through the PrismaClient docs exhaustively and can't seem to find the solution. My thoughts are that it should happen in the shelf controller/service, but I am not certain of this. Currently I have an end point defined in shelves.controller.ts:

@Get(':id/boxes') 
@ApiOkResponse({ type: ShelfEntity, isArray: true })
getBoxes(@Param('id') id:string ){
    return this.shelvesService.getBoxes(id)
}

with ShelfEntity defined as:

export class ShelfEntity implements Shelf {
    @ApiProperty({ required: true })
    id: string
}

which queries the prisma client in shelves.service.ts for boxes filtered by the shelfId:

getBoxes(id: string) {
    return this.prisma.shelf.findUnique({ where: {id}, select: { boxes:true })
}

The expected response from this GET call is an array of Box objects (I base this expectation on https://www.prisma.io/docs/concepts/components/prisma-client/crud#select-a-subset-of-fields ) but I am getting a 404. Any help offered would be greatly appreciated.

Please check for your controller if the actual call lead to the services. 404 should related to NestJs side when it can't access your route. The prisma select / include worked fine in my case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM