Product CRUD
This commit is contained in:
@@ -1,22 +1,77 @@
|
||||
import {Request, Response} from 'express';
|
||||
import {db} from '../../db/index';
|
||||
import {eq} from 'drizzle-orm';
|
||||
import { productsTable } from '../../db/productsSchema';
|
||||
|
||||
export function listProducts(req: Request, res: Response) {
|
||||
res.send ('listProducts');
|
||||
export async function listProducts(req: Request, res: Response) {
|
||||
try{
|
||||
const products = await db.select().from(productsTable);
|
||||
res.json(products);
|
||||
} catch (e) {
|
||||
res.status(500).send(e);
|
||||
}
|
||||
}
|
||||
|
||||
export function getProductById(req: Request, res: Response) {
|
||||
res.send ('getProductById');
|
||||
export async function getProductById(req: Request, res: Response) {
|
||||
try{
|
||||
const {id} = req.params;
|
||||
const product = await db
|
||||
.select()
|
||||
.from(productsTable)
|
||||
.where(eq(productsTable.id, Number(id)));
|
||||
if (product.length == 0) {
|
||||
res.status(404).send({message: "Product not found"});
|
||||
} else {
|
||||
res.json(product);
|
||||
}
|
||||
//console.log(product.length);
|
||||
|
||||
} catch (e) {
|
||||
res.status(500).send(e);
|
||||
}
|
||||
}
|
||||
|
||||
export function createProduct(req: Request, res: Response) {
|
||||
console.log (req.body);
|
||||
res.send ('createProduct');
|
||||
export async function createProduct(req: Request, res: Response) {
|
||||
try{
|
||||
const productId = await db
|
||||
.insert(productsTable)
|
||||
.values(req.body)
|
||||
.$returningId()
|
||||
//const [product] = await db.insert(productsTable).values(req.body).Returning()
|
||||
//Postgresql can return series of products so we can capture the first one from array[]
|
||||
res.status(201).json(productId);
|
||||
} catch (e) {
|
||||
res.status(500).send(e);
|
||||
}
|
||||
}
|
||||
|
||||
export function updateProduct(req: Request, res: Response) {
|
||||
res.send ('updateProduct');
|
||||
export async function updateProduct(req: Request, res: Response) {
|
||||
try{
|
||||
const id = Number(req.params.id);
|
||||
const updatedFields = req.body;
|
||||
|
||||
const result = await db
|
||||
.update(productsTable)
|
||||
.set(updatedFields)
|
||||
.where(eq(productsTable.id, id))
|
||||
|
||||
console.log(result);
|
||||
|
||||
} catch (e) {
|
||||
res.status(500).send(e);
|
||||
}
|
||||
}
|
||||
|
||||
export function deleteProduct(req: Request, res: Response) {
|
||||
res.send ('deleteProduct');
|
||||
export async function deleteProduct(req: Request, res: Response) {
|
||||
try{
|
||||
const id = Number(req.params.id);
|
||||
|
||||
const [deletedProduct] = await db
|
||||
.delete(productsTable)
|
||||
.where(eq(productsTable.id , id));
|
||||
|
||||
console.log(deleteProduct);
|
||||
} catch (e) {
|
||||
res.status(500).send(e);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user