What is the best way to retrieve all the subsections associated with a specific section?

Currently utilizing Nestjs for the backend and in the process of developing an API call that will return all subsections pertaining to a specific section. Seeking guidance or suggestions on how to accomplish this task.

If a GET request is made to /subsection/167 (where 167 represents the section ID), the endpoint should provide all subsections associated with that particular section.

Entity

@PrimaryGeneratedColumn({
    type: "int",
    name: "Id",
})
id: number;

@Column("nvarchar", {
    nullable: false,
    unique: true,
    name: "Name"
})
name: string;

@Column("nvarchar", {
    nullable: false,
    name: "ParentId"
})
parentId: number;

Controller

@Get('/subsection/:parentId')
async getHelpSubSection(@Req() req, @Param() params):Promise<HelpEntity[]>{
    return this.helpService.getHelpbySubSection(req.user, params.id);
}

Service

constructor(@InjectRepository(HelpEntity) private readonly helpRepo: Repository<HelpEntity>,

async getHelpbySubSection(gmid: string, id: number) : Promise<any>{
    let check = await this.checkIfAdmin(gmid);
    if (!check) {
        throw new HttpException('Unauthorized', 401);
    } else {
        const res = await this.helpRepo.findOne()
        if (!res) {
            throw new NotFoundException(`This ID: ${id} is not found`)
        }
        return res;
    }
}

In my database, all parent sections have NULL values in the ParentId field.

https://i.sstatic.net/PGFQT.png

Answer №1

To modify the findone method to search based on your specific criteria, follow these steps:

 constructor(@InjectRepository(HelpEntity) private readonly helpRepo: Repository<HelpEntity>,

async getHelpbySubSection(gmid: string, id: number) : Promise<any>{
    let check = await this.checkIfAdmin(gmid);
    if (!check) {
        throw new HttpException('Unauthorized', 401);
    } else {
        const res = await this.helpRepo.find({parentId : id})
        if (!res) {
            throw new NotFoundException(`This ID: ${id} is not found`)
        }
        return res;
    }
}

Update
and in your controller fix the name of the parameter

  @Get('/subsection/:parentId')
async getHelpSubSection(@Req() req, @Param() params):Promise<HelpEntity[]>{
    return this.helpService.getHelpbySubSection(req.user, params.parentId);
}

For further information, refer to: find-options

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

Utilize Typescript to ensure uniformity in object structure across two choices

Looking to create a tab component that can display tabs either with icons or plain text. Instead of passing in the variant, I am considering using Typescript to verify if any of the icons have an attribute called iconName. If one icon has it, then all othe ...

"Unlocking the Potential: A Step-by-Step Guide to Finding Your PageID in a Facebook

I've integrated Facebook Requests ( https://developers.facebook.com/docs/games/requests/ ) into my Page Tab App to invite users. I have successfully set up a canvas for this functionality, but now I want to redirect users who click on the invite and l ...

Tips for testing and verifying the call to a specific Firebase method within a function using Jest

Within the file App.ts, I am utilizing the method firebase.auth().signInWithEmailAndPassword(email, password). Now, my objective is to conduct a unit test to ensure that when the myAuthenticationPlugin.authenticate(email, password) method is invoked from ...

Incorporating a skeletal design effect into a table featuring sorting and pagination options

Is there a way to implement the Skeleton effect in a MUI table that only requires sorting and pagination functionalities? I tried using the 'loading' hook with fake data fetching and a 3-second delay, but it doesn't seem to work with DataGri ...

implementing Angular2's Material Design with ES6

Can Angular2 Material2 be started with ES6? I have attempted to discover a solution but was unsuccessful. I also examined the git repository and noticed that all code is currently in TypeScript Does this mean we cannot use it with ES6? Is there an alte ...

Executing React's useEffect hook twice

As I work on developing an API using express.js, I have implemented an authentication system utilizing JWT tokens for generating refresh and access tokens. During testing with Jest, Supertest, and Postman, everything appears to be functioning correctly. O ...

ability to reach the sub-element dictionaries in typescript

class ProvinciaComponent extends CatalogoGenerico implements OnInit, AfterViewInit { page: Page = new Page({sort: {field: 'description', dir: 'asc'}}); dataSource: ProvinciaDataSource; columns = ['codprovi ...

How to access individual reactive form instances within an ngFor loop in Angular

I've been grappling with this issue for a few hours now, trying to find a solution that doesn't involve adding fields dynamically. All I need is the ability to access the properties of each form instance, but currently, it only displays one insta ...

How can Bootstrap 4 be utilized to achieve a responsive height on a single page application with no scrolling?

Embarking on the journey of responsive website design as a beginner in front end development, I am currently working on creating a basic angular chat application with bootstrap. Keeping responsiveness in mind throughout the design process is my goal, but I ...

Can the type of a prop be specified in the parent component before it is passed down to the children components that utilize the same prop?

In my codebase, I have a component called NotFoundGuard. This component only renders its children if a certain condition is true. Otherwise, it displays a generic fallback component to prevent redundancy in our code. I am trying to figure out if there is ...

Having difficulty properly streaming UI components with Vercel's AI-SDK

Recently, I've been diving into the new Vercel's AI-SDK to expand my skills. My current project involves developing a persona generator that takes specific guidelines as inputs and generates persona attributes according to a given Zod schema. B ...

The error message "TypeError: 'results.length' is not an object" occurred within the Search Component during evaluation

Having trouble with a search feature that is supposed to display results from /api/nextSearch.tsx. However, whenever I input a query into the search box, I keep getting the error message TypeError: undefined is not an object (evaluating 'results.lengt ...

Is it possible to loop through every EventEmitter that is adorned with @Output() in Angular 2?

In order to achieve my goal, I am aiming to iterate through all the EventEmitter instances decorated with @Output within a given component. For example: my-component @Component({ moduleId: module.id, selector: "my-component", templa ...

Unable to modify state upon submission of a form

I am facing an issue where I need to update the state on the main page, but the values are updated three levels down... This particular component is responsible for fetching all the cities, storing the data in the State, and then mapping through the citie ...

Why is Firebase Deploy only detecting 1-2 files? It might be due to the default index of Firebase hosting

I'm currently in the process of deploying my Angular App to Firebase Hosting. However, I am encountering an issue where it only displays the default firebase index hosting with no changes. To set up the deployment, I have used firebase init and speci ...

Tips for populating all the ionic form fields using speech recognition technology

In the process of developing an Ionic 4 application, I am faced with a challenge where I need to fill in multiple form fields using the Ionic speech-recognition plugin. Currently, I am only able to populate one field at a time. What I am looking for is a w ...

Cookie-setting isn't functioning properly on Opera and Firefox browsers, but it is working correctly on Postman when using Express

After spending an entire day researching, I have yet to find a solution to my problem despite trying everything possible. I suspect that the issue lies with the browser's security policy because my server and client are both running on different loca ...

Angular button disable feature malfunctioning

In my current setup, I have included a date picker along with a save button. One issue I am facing is that the save button gets disabled when the date is not available. Despite the code working fine in most scenarios, there seems to be an issue with the di ...

Securely import TypeScript modules from file paths that are dynamically determined during execution

Imagine you have a structure of TypeScript code and assets stored at a specific URL, like between a CDN and a debug location. You want to import the main module and ensure the rest of the structure is imported correctly only when needed, without repeating ...

Removing items from Google Cloud Storage using Google Cloud API, Node.js, and the request.del() method

I am facing an issue while trying to delete an object using request and the Google API. Despite following the instructions provided by Google Cloud Platform, I am unable to get it working. Could someone please assist me in resolving this problem? Thank y ...