-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
97 lines (85 loc) · 2.33 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
const express = require('express')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
const shortid = require('shortid')
const app = express()
app.use(bodyParser.json())
app.use("/", express.static(__dirname + "/build"))
app.get("/", (req, res) => res.sendFile(__dirname + "/build/index.html"))
mongoose.connect(
process.env.MONGODB_URL ||
"mongodb://localhost/react-store-db", {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
})
const Product = mongoose.model(
"products",
new mongoose.Schema({
_id: { type: String, default: shortid.generate },
title: String,
image: String,
description: String,
price: Number,
avaliableSizes: [String],
})
)
app.get("/api/products", async(req, res)=>{
const products = await Product.find({})
res.send(products)
})
app.post("/api/products", async(req, res) => {
const newProduct = new Product(req.body)
const savedProduct = await newProduct.save()
res.send(savedProduct)
})
app.delete("/api/products/:id", async(req, res) => {
const deletedProduct = await Product.findByIdAndDelete(req.params.id)
res.send(deletedProduct)
})
const Order = mongoose.model("order", new mongoose.Schema(
{
_id: {
type: String,
default: shortid.generate,
},
email: String,
name: String,
address: String,
total: Number,
cartItems: [
{
_id: String,
title: String,
price: Number,
count: Number,
},
],
},
{
timestamps: true,
}
))
app.post("/api/orders", async (req, res) => {
if (
!req.body.name ||
!req.body.email ||
!req.body.address ||
!req.body.total ||
!req.body.cartItems
) {
return res.send({ message: "Data is required." })
}
const order = await Order(req.body).save()
res.send(order)
})
app.get("/api/orders", async(req, res) => {
const orders = await Order.find({})
res.send(orders)
})
app.delete("/api/orders/:id", async(req, res) => {
const order = await Order.findByIdAndDelete(req.params.id)
res.send(order)
})
const port = process.env.PORT || 5000
app.listen(port, () => console.log("server at http://localhost:5000"))