Tips for Configuring a Nestjs Query Using TypeORM to Retrieve Several Entries

When I send this specific URL from my Angular application:

http://localhost:3000/api/skills?category_id=2

The main issue revolves around how to modify the code in order to successfully retrieve all skills with a category_id of 2. It is important to note that just fetching the skill_id individually is not the goal here. Each record contains the following fields:

skill_id
skill_name
category_id

Within the skills.controller file, I have made attempts to use the @Get param for this purpose, without success. The console.log function never seems to be triggered. Furthermore, I am unclear on how to instruct the service to fetch all skill records matching a specified category_id.

  @Get('?category_id')
  public async getSkillsByCategory(@Param('category_id') categoryId) {
    console.log('skills recordId in controller: ', categoryId.id);
    return this.skillsService.getSkillsByCategory(categoryId.id);
  }

Inside the skills.service file, there exists a method aimed at retrieving skills based on their category_id. However, it does not effectively communicate this requirement to the database, particularly Postgres. It appears that a different approach is necessary due to the unique behavior of the category_id column.

  async getSkillsByCategory(categoryId) {
    console.log('categoryId in service', categoryId);
    return await this.skillsRepository.find(categoryId);
  }

Answer №1

Assuming that the main path for your skills is

http://localhost:3000/api/skills/
, modify your controller as follows:

  import { ParseIntPipe } from '@nestjs/common';
  // Utilize ParseIntPipe to ensure id is a number for validation purposes
  
  @Get('category/:id')  //  or  @Get('/category/:id')
  public async getSkillsByCategory(@Param('id', new ParseIntPipe()) id) {
    return this.skillsService.getSkillsByCategory(id);
  }

Update your service implementation as shown below:

async getSkillsByCategory(id) {
  return await this.skillsRepository.find({ category_id: id });
}

Finally, make a GET request to

http://localhost:3000/api/skills/category/2
.

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

Preserving reference equality while passing props in React

Consider a scenario where a function dynamically generates some props for a component, and you want to pass all of them without specifying each individual prop that the function might generate. Typically, this can be achieved using the spread operator. How ...

Angular dependency issue: Expected '{' or ';' for @types/node

I encountered an error while running "ng serve" in my Angular application. Originally built as Angular 2, it was upgraded to Angular 8 (with attempts at versions 6 and 7 along the way). However, after migrating from Angular 5, I started experiencing errors ...

Mastering parameter passing in Node.js functions: A comprehensive guide

As I embark on my journey with node js (refer to the question), please be patient as I navigate through this new territory. To clarify my query, I have developed a function to be invoked in another JS file: exports.test = function(req, res){ connection ...

Issue with HTML 5 audio player not functioning correctly in Chrome browsers when trying to forward or rewind playback

I am encountering an issue with running the HTML5 audio player in Chrome. It works perfectly fine in IE 9+ and Firefox. I have implemented JavaScript functions for forwarding and rewinding the audio player on F7 and F8 key press. These functions work seaml ...

Can a ternary operator be used within an index type query when extending a partial type?

Can anyone provide a detailed explanation of the process unfolding in this snippet? I'm having trouble grasping how this code leads to a type declaration. type ModalErrors = Partial< { [key in keyof InputGroup]: InputGroup[key] extends Speci ...

When importing an Angular 9 library, the error message "The value at index 4 within MyCommonLibraryModule's NgModule.imports is not a valid reference" is displayed

Having two Angular projects that share a common code base through an Angular library, I decided to upgrade them from version 8 to 9 using the ng update command. However, after running the migration scripts, I noticed changes in the tsconfig.app.json file: ...

Finding elements in an array based on a specific string contained within a property

I am currently working on filtering JSON data to specifically search for job roles that begin with a particular string. The structure of the JSON is as follows : "periods": [ { "periodName": "Week1", "teamName": "Tango", ...

Upon installing a global npm package, the system encountered an error stating: 'File or directory not found: ENOENT'

After successfully publishing my first Node.js CLI tool package on npm, I encountered an issue when trying to test it by installing it locally. The warning message "Error: ENOENT: no such file or directory" kept showing up. Steps for Reproduction To start ...

What is the best way to create a layout with two images positioned in the center?

Is it possible to align the two pictures to the center of the page horizontally using only HTML and CSS? I've tried using this code but it doesn't seem to work: #product .container { display: flex; justify-content: space-between; flex-w ...

Transforming an Ext.data.TreeStore data structure into a JSON format

How can I convert an Ext.data.TreeStore to a string for saving to Local Storage? I tried using Ext.encode() but it's giving me a circular structure error. Has anyone encountered this issue and found a workaround? ...

The fixed position setting does not anchor the elements to the bottom of a container

When applying the following styles: #fullpage-menu > .gradient { position: fixed; bottom: 0; left: 0; width: 100%; height: 0.3rem; } To the element with ID #fullpage-menu, which is styled as follows: #fullpage-menu { height: 100 ...

I am looking to generate div elements using JavaScript to avoid the tedious task of individually creating numerous divs

Instead of manually typing out multiple div tags in the HTML, I would like to dynamically generate them using JavaScript and display them on the page. Below is an attempt at achieving this, but it appears to not be functioning correctly. var arr = {}; f ...

Utilize JSON parsing to extract and store data into an object

I'm currently working on extracting specific objects from a parsed JSON stored within an object named data.json. var data = { json: '', text: '', welcome: '', q1: '', } let foo = await fetch(spr ...

What could be causing me to receive two builds when using Webpack?

I am trying to capture the hash of the build by using a callback function in webpack: const compiler = webpack(webpackConfig, function (err, stats) { debug("Hash", stats.hash) }) However, I am encountering an issue where two builds are generated and on ...

What is causing the issue in locating the assert package for VS Code and TypeScript?

My main issue lies with the pre-installed node libraries (path, fs, assert). Let me outline the process that leads to this problem: Begin by launching Visual Studio. Select File > Open Folder, then pick the root core-demo folder. In the file panel, loc ...

What is the reason for the request body being undefined?

I have a JavaScript file named index.js that contains: const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const db = require('./db'); const movieRouter = re ...

Vue.js is displaying one less item

Recently I started working with Vuejs and encountered an unexpected issue in my application. The purpose of my app is to search for channels using the YouTube API and then display those channels in a list. However, when I try to render the list of subscri ...

Unlocking the secret to obtaining durable identity provider tokens for JavaScript in web browsers

Currently, I am working on implementing browser-side JavaScript code for login with Facebook, Amazon, Twitter, and Google using Cognito. I have reached a point where I am able to obtain client tokens for all four platforms. However, the issue is that thes ...

What is the best way to insert a React component or raw HTML into another React component?

Dealing with raw HTML markup returned from an AJAX call can be tricky in React. I've tried using dangerouslySetInnerHTML, but React just throws errors when I do. It's like trying to navigate through a maze. After some trial and error, I decided ...

What is the best way to change the order of rows and columns in

Is there a way to rotate a table using jQuery? Maybe with a function or some other method? For instance, if I have a table structured like this: <table> <tr> <th></th> <th></th> <th>&l ...