Building a NestJS/Prisma RESTful API to retrieve data from a related field

I am diving into creating my very own Rest API using Nestjs and Prisma for the first time. This project is a basic representation of an inventory management system, keeping things simple with shelves and boxes to store items. The structure in place has tables in a Postgres DB that define the relationships between shelves and boxes (excluding other models 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 have successfully implemented functionalities like creating, fetching, filtering, and deleting data. However, I am facing a challenge when attempting to retrieve all boxes on a specific shelf, followed by retrieving all items within a particular box.

Despite extensive research through PrismaClient documentation, I haven't been able to find a solution to this issue. My current belief is that the logic should reside in the shelf controller/service, but I'm not entirely sure. At present, I have an endpoint set up in shelves.controller.ts:

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

The ShelfEntity definition looks like this:

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

This endpoint calls the shelves.service.ts file, which queries the Prisma client to fetch boxes filtered by shelfId:

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

Based on the expected response described in Prisma Documentation, I should receive an array of Box objects from this GET request. However, I am encountering a 404 error. Any assistance or guidance provided would be immensely appreciated.

Answer №1

Make sure to verify that your controller is properly handling the service calls. A 404 error may be linked to an issue on the NestJs side if it is unable to reach your specified route. I had no problems with prisma select / include in my scenario.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a method to accurately pinpoint the specific type?

Is there a way to optimize the validateField function to narrow down the type more effectively? type TStringValidator = (v: string) => void; type TNumberValidator = (v: number) => void; type TFields = 'inn' | 'amount'; interface ...

Testing NestJS Global ModulesExplore how to efficiently use NestJS global

Is it possible to seamlessly include all @Global modules into a TestModule without the need to manually import them like in the main application? Until now, I've had to remember to add each global module to the list of imports for my test: await Tes ...

When coding in JavaScript, the value of "this" becomes undefined within a class function

I'm facing an issue with my TypeScript class that contains all my Express page functions. When I try to access the class member variable using this, I get an 'undefined' error: class CPages { private Version: string; constructor(ver ...

Steer clear from using the implicit 'any' type while utilizing Object.keys in Typescript

I have a unique situation where I need to loop over an Object while maintaining their type without encountering the error "Element implicitly has an 'any' type because 'ContactList' has no index signature". Despite extensive discussion ...

What are the steps to effectively utilize an interface within a TypeScript file that contains its own internal import?

Currently, I am in the process of developing a React JavaScript project using WebStorm and attempting to enable type hinting for our IDEs (including VS Code) by utilizing TypeScript interfaces and JSDoc annotations. Our goal is to potentially transition to ...

Issue encountered when working with Next Auth and TypeScript: The argument type 'string | undefined' cannot be assigned to the parameter type 'string | Buffer'

Encountering a TypeScript error that states: "Argument of type 'string | undefined' is not assignable to parameter of type 'string | Buffer'." An attempt to integrate NextAuth into a Next.js 14 application and configure logi ...

Adding an image to a Select Option label in React: A simple guide

As a newcomer to React, I am experimenting with creating a drop-down menu that includes images in the labels. My approach involves using a function to gather values from a map and construct an id: label pair to display as options in the drop-down. Both the ...

How to retrieve a value from a base64-decoded string in Angular 6?

I successfully decoded a Base64 string using the xml2js library and obtained the following XML value: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <svg width="293" height="102" viewBox="0 0 293 102" xmlns="http://www.w3.org/2000/svg" ...

DynamoDB query results in a null return when listing maps

My query involves a DynamoDB that contains an attribute named 'Multiple Units' with the structure: List [ Map { Map { S }, S }, ... ] I have been testing a lambda function locally: module.exports.getByAddress = async (event) => { const para ...

What is the correct method for typing sagas?

After diligently following the official redux documentation for integrating with TypeScript, which can be found at https://redux.js.org/recipes/usage-with-typescript, I successfully typed actions, reducers, react components, and more. However, my progress ...

Error encountered while retrieving data from Firebase and storing it in an array within an IONIC application

I am currently working on a function that retrieves data from Firebase's real-time database and stores it in an array for mapping in React. However, I am encountering a TypeScript error that I'm having trouble resolving. The error message reads ...

Looking for guidance on setting up Honeybadger logging in NestJS. Can anyone help with this?

While using NestJS which utilizes express, I came across Honeybadger's express middleware. However, I am having trouble implementing it into my current main.ts file setup. import { NestFactory } from '@nestjs/core'; import { AppModule } from ...

Using React to make an API call without utilizing hooks

Hello, I am currently working on developing a webpart using SharePoint and React. However, I am facing some issues with fetching data from a simple API. export default class Testing100 extends React.Component<ITesting100Props, {}> { constructor(p ...

What is the reason behind VS Code not showing an error when executing the command line tsc shows an error message?

Deliberately introducing a typo in my code results in an error. Here is the corrected code: declare const State: TwineState; If I remove the last character and then run tsc on the command line, it throws this error: tsc/prod.spec.ts:7:22 - error TS2304: ...

Modifying message data in socket.io with Nestjs

One way to edit the value of message data when it's not null is by using this code: context.switchToWs().getData().custom = true However, what can be done to change it if the message data is null? ...

Reorganizing items within an ArrayCollection using RESTAPI

Consider this scenario: I have an array collection called $items, and I have implemented a method called removeItem in my SomeEntity entity class, public function removeItem(Item $item) { $this->items->removeElement($item); return $this; } ...

How can I configure a mocked dependency in Jest to return a specific value in a function?

I am currently working on simulating a mongoose model to facilitate unit testing for an express controller. To keep things simple, I've removed all unnecessary code and provided below the specific scenario I'm dealing with. Here's the snippe ...

Is there a method to automatically select or deselect a checkbox based on the incoming value in Angular?

When new data comes in, the table gets populated and I can't specify that "A" should be checked while "D" shouldn't. re(ref: getrefactormodel, count:number){ let data= this.fb.group({ word_to_rename: [ref.word_to_rename, Vali ...

Trouble encountered with the implementation of setValue on placeholder

When I send the value for age, it is being treated as a date in the API that was built that way. However, when I use setValue to set the form value and submit the form, it also changes the placeholder text, which is not what I want. I would like the placeh ...

Tips for displaying bar chart labels effectively with ChartJS

I am working on an Angular project and I would like to incorporate a barchart using ChartJS. The data for this chart can vary in size, sometimes being very large. One issue I have encountered is that when the number of data points is large, the labels ove ...