Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

268
Visualizações
I find the CRUD request doesn't work: Nodejs

I work for an Nodejs API and this is an handler file:

import express, { Request, Response } from 'express';
import { ProductStore, Product } from '../models/products';

const store = new ProductStore();

/* 
export type Product = {
    id?: number;
    name: string;
    price: number;
    category?: string;
};
*/

const index = async (_req: Request, res: Response) => {
    const products = await store.index();
    res.json(products);
};

const show = async (_req: Request, res: Response) => {
    const product = await store.show(_req.body.id);
    res.json(product);
};

const productRoutes = (app: express.Application) => {
    app.get('/products', index);
    app.get('/products/:id', show);
    app.post('/products', create);
    app.delete('/products', destroy);
};

export default productRoutes;

The respective model file is:

import client from '../database';

export type Product = {
    id?: number;
    name: string;
    price: number;
    category?: string;
};

export class ProductStore {
    async index(): Promise<Product[]> {
        try {
            // @ts-ignore
            const conn = await client.connect();
            const sql = 'SELECT * FROM products';

            const result = await conn.query(sql);

            conn.release();

            return result.rows;
        } catch (err) {
            throw new Error(`Could not GET products with error: ${err}`);
        }
    }

    async show(id: number): Promise<Product> {
        try {
            const sql = 'SELECT * FROM products WHERE id=($1)';
            // @ts-ignore
            const conn = await client.connect();

            const result = await conn.query(sql, [id]);

            conn.release();

            return result.rows[0];
        } catch (err) {
            throw new Error(`Could not find product ${id} with error: ${err}`);
        }
    }
}

When I try to index all the products, this works well, but, I can't fetch only one product for show.

enter image description here

The API is here in case someone want to look: https://github.com/Chaklader/StorefrontAPI

The SQL query works in the Postgres terminal. What's the issue here?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Replace your second query string with this:

const sql = 'SELECT * FROM products WHERE id=$1';
over 4 years ago · Santiago Trujillo Relatório

0

This issue was as I provided the parameter with the URL, I will need to extract it accordingly and not from the body. This is the code that works:

const show = async (_req: Request, res: Response) => {

    const c = parseInt(_req.params.id);
    const product = await store.show(c);
    res.json(product);
};

Besides, the SQL query mentioned in the answer above is incorrect and can be used as it is provided in the question.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda