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.
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?
Replace your second query string with this:
const sql = 'SELECT * FROM products WHERE id=$1';
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.