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.
76 lines
1.9 KiB
TypeScript
76 lines
1.9 KiB
TypeScript
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", verifyAuthToken, index);
|
|
app.get("/orders/:id", verifyAuthToken, read);
|
|
app.post("/orders", verifyAuthToken, create);
|
|
app.post("/orders/:id/products", verifyAuthToken, addProduct);
|
|
app.delete("/orders/:id/products", verifyAuthToken, deleteProduct);
|
|
};
|
|
|
|
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.user_id),
|
|
};
|
|
|
|
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),
|
|
};
|
|
const addedProduct = await store.addProduct(orderProductInfo);
|
|
res.json(addedProduct);
|
|
} catch (err) {
|
|
res.status(400);
|
|
res.json(err);
|
|
}
|
|
};
|
|
|
|
const deleteProduct = async (req: Request, res: Response) => {
|
|
try {
|
|
const deletedProduct = await store.deleteProduct(parseInt(req.params.id));
|
|
res.json(deletedProduct);
|
|
} catch (err) {
|
|
res.status(400);
|
|
res.json(err);
|
|
}
|
|
};
|
|
|
|
export default orderRoutes;
|