|
|
|
import express, { Request, Response } from 'express'
|
|
|
|
import { Order, OrderProduct, OrderStore } from '../models/order'
|
|
|
|
import { verifyAuthToken } from './utils'
|
|
|
|
|
|
|
|
const orderRoutes = (app: express.Application) => {
|
|
|
|
app.get('/orders', index)
|
|
|
|
app.get('/orders/:id', read)
|
|
|
|
app.post('/orders', verifyAuthToken, create)
|
|
|
|
app.post('/orders/:id/products', verifyAuthToken, addProduct)
|
|
|
|
}
|
|
|
|
|
|
|
|
const store = new OrderStore()
|
|
|
|
|
|
|
|
const index = async (req: Request, res: Response) => {
|
|
|
|
try {
|
|
|
|
const orders = await store.index()
|
|
|
|
res.json(orders)
|
|
|
|
} catch (err) {
|
|
|
|
res.status(400)
|
|
|
|
res.json(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const read = async (req: Request, res: Response) => {
|
|
|
|
try {
|
|
|
|
const order = await store.read(parseInt(req.params.id))
|
|
|
|
res.json(order)
|
|
|
|
} catch (err) {
|
|
|
|
res.status(400)
|
|
|
|
res.json(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
const create = async (req: Request, res: Response) => {
|
|
|
|
try {
|
|
|
|
const orderInfo: Order = {
|
|
|
|
status: req.body.status,
|
|
|
|
user_id: parseInt(req.body.userId)
|
|
|
|
}
|
|
|
|
|
|
|
|
console.log('orderInfo', orderInfo)
|
|
|
|
|
|
|
|
const newOrder = await store.create(orderInfo)
|
|
|
|
res.json(newOrder)
|
|
|
|
} catch (err) {
|
|
|
|
res.status(400)
|
|
|
|
res.json(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const addProduct = async (req: Request, res: Response) => {
|
|
|
|
try {
|
|
|
|
const orderProductInfo: OrderProduct = {
|
|
|
|
order_id: parseInt(req.params.id),
|
|
|
|
quantity: parseInt(req.body.quantity),
|
|
|
|
product_id: parseInt(req.body.product_id)
|
|
|
|
}
|
|
|
|
console.log(orderProductInfo)
|
|
|
|
const addedProduct = await store.addProduct(orderProductInfo)
|
|
|
|
res.json(addedProduct)
|
|
|
|
} catch (err) {
|
|
|
|
res.status(400)
|
|
|
|
res.json(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
export default orderRoutes
|