-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
97 lines (84 loc) · 1.97 KB
/
server.js
File metadata and controls
97 lines (84 loc) · 1.97 KB
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 cors = require("cors");
const app = express();
app.use(bodyParser.json());
mongoose.connect("mongodb://localhost/shopping-app-db", {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
});
const Product = mongoose.model(
"products",
new mongoose.Schema({
id: { type: String, default: shortid.generate },
title: String,
description: String,
image: String,
price: Number,
sizes: [String],
})
);
const corsOptions = {
origin: "http://localhost:3000",
};
app.use(cors(corsOptions));
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) => {
debugger;
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);
});
const port = process.env.PORT || 5000;
app.listen(port, () => console.log("serve at http://localhost:5000"));