-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
91 lines (81 loc) · 2.37 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
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const shortid = require("shortid");
const app = express();
app.use(bodyParser.json());
// for build by these 2 line we can see project on localhost:5000
app.use("/", express.static(__dirname + "/build"));
app.get("/", (req, res) => res.sendFile(__dirname + "/build/index.html"));
mongoose.connect(
process.env.MOONGODB_URL || "mongodb://localhost/react-shop-cart-db",{
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology:true,
})
//Creating product Model
const Product = mongoose.model(
"products",
new mongoose.Schema({
_id: { type: String, default: shortid.generate },
title: String,
description: String,
image: String,
price: Number,
availableSize: [String],
})
);
app.get("/api/products", async (req, res) =>{
const products = await Product.find({}); //Getiing all products
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 deleteProduct = await Product.findByIdAndDelete(req.params.id);
res.send(deleteProduct);
})
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("serve at http://localhost:5000"));