You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.4 KiB
TypeScript

import express, {request, Request, response, Response} from 'express'
import { Product, ProductStore } from '../models/product'
const productRoutes = (app: express.Application) => {
app.get('/products', index)
app.get('/products/:id', show)
app.post('/products', create)
app.delete('/products/:id', destroy)
}
const store = new ProductStore()
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.params.id)
res.json(product)
}
const create = async (req: Request, res: Response) => {
try {
const productInfo: Product = {
name: request.body.name,
price: request.body.price,
}
const newProduct = await store.create(productInfo);
res.json(newProduct)
} catch (err) {
res.status(400)
res.json(err)
}
}
const update = async (req: Request, res: Response) => {
try {
const product = await store.update(req.body);
res.json({
name: request.body.name,
price: request.body.price,
})
} catch (err) {
throw new Error(`Can't update product. ${err}`)
}
}
const destroy = async (req: Request, res: Response) => {
const deleted = await store.delete(req.body.id)
res.json(deleted)
}
export default productRoutes