【发布时间】:2021-10-11 19:43:03
【问题描述】:
我为 Nodejs API 工作,这是一个处理程序文件:
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;
各自的模型文件是:
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}`);
}
}
}
当我尝试为所有产品编制索引时,效果很好,但是,我无法只获取一个产品进行展示。
API 在这里,以防有人想查看:https://github.com/Chaklader/StorefrontAPI
SQL 查询在 Postgres 终端中运行。这里有什么问题?
【问题讨论】:
标签: node.js typescript visual-studio-code