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.
80 lines
1.8 KiB
TypeScript
80 lines
1.8 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', create)
|
|
app.put('/products/:id', update)
|
|
app.delete('/products/:id', destroy)
|
|
}
|
|
|
|
const store = new ProductStore()
|
|
|
|
const index = async (req: Request, res: Response) => {
|
|
try {
|
|
const products = await store.index();
|
|
res.json(products);
|
|
console.log('working products index')
|
|
} catch (err) {
|
|
console.log('error products index')
|
|
res.status(400)
|
|
res.json(err)
|
|
}
|
|
|
|
}
|
|
|
|
const show = async (req: Request, res: Response) => {
|
|
try {
|
|
const product = await store.show(parseInt(req.params.id))
|
|
res.json(product)
|
|
} catch (err) {
|
|
res.status(400)
|
|
res.json(err)
|
|
}
|
|
|
|
}
|
|
|
|
const create = async (req: Request, res: Response) => {
|
|
|
|
try {
|
|
const productInfo: Product = {
|
|
name: req.body.name,
|
|
price: req.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: req.body.name,
|
|
price: req.body.price,
|
|
})
|
|
} catch (err) {
|
|
res.status(400)
|
|
res.json(err)
|
|
}
|
|
}
|
|
|
|
const destroy = async (req: Request, res: Response) => {
|
|
try {
|
|
const deleted = await store.delete(req.body.id)
|
|
res.json(deleted)
|
|
} catch (err) {
|
|
res.status(400)
|
|
res.json(err)
|
|
}
|
|
|
|
}
|
|
|
|
|
|
export default productRoutes |