-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
240 lines (217 loc) · 7.75 KB
/
index.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
const express = require("express");
const cors = require("cors");
const jwt = require("jsonwebtoken");
const cookieParser = require("cookie-parser");
require("dotenv").config();
const { MongoClient, ServerApiVersion, ObjectId } = require("mongodb");
const app = express();
const port = process.env.PORT || 5000;
//Middlewares
const origin = ["http://localhost:5173", "https://piquant-b9a11.web.app"];
app.use(
cors({
origin: origin,
credentials: true,
// methods: ["GET", "POST", "PUT", "DELETE","PATCH"],
})
);
app.use(express.json());
app.use(cookieParser());
const verifyToken = async (req, res, next) => {
const token = req?.cookies?.token;
// console.log(token);
if (!token) {
return res.status(401).send({ message: "unauthorized access" });
}
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
if (err) {
return res.status(401).send({ message: "unauthorized access" });
}
req.user = decoded;
next();
});
};
// const uri = `mongodb://localhost:27017`;
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.jr4kdoi.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0`;
// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
},
});
const foods_collection = client.db("PIQUANT-B9A11").collection("foods");
const reviews_collection = client.db("PIQUANT-B9A11").collection("reviews");
const purchases_collection = client.db("PIQUANT-B9A11").collection("purchases");
async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
// await client.connect();
// POST :: post method to set JWT token in client side cookie
app.post("/jwt", async (req, res) => {
const user = req.body;
// console.log(user);
const token = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, {
expiresIn: "1h",
});
res
.cookie("token", token, {
httpOnly: true,
secure: true,
sameSite: "none",
})
.send({ seccess: true });
});
// POST :: This method use for clear browser Cookie when user logout there account.
app.post("/logout", async (req, res) => {
const user = req.body;
// console.log(user);
res.clearCookie("token", { maxAge: 0 }).send({ seccess: true });
});
// GET :: get multiple foods from foods collection in database
app.get("/foods", verifyToken, async (req, res) => {
if (req?.query?.authorEmail !== req?.user?.email) {
return res.status(403).send({ message: "forbidden access" });
}
let quary = {};
if (req.query.searchFor) {
// console.log(req.query.searchFor);
quary = { foodName: { $regex: new RegExp(req.query.searchFor, "i") } };
} else if (req.query.authorEmail) {
// console.log(req.query.authorEmail);
quary = { "author.authorEmail": req.query.authorEmail };
}
const result = await foods_collection.find(quary).toArray();
res.send(result);
});
// GET :: get single food data from foods collection in database
app.get("/food/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await foods_collection.findOne(query);
res.send(result);
});
// GET :: get top 6 foods from foods collection in database
app.get("/top-foods", async (req, res) => {
let query = {};
const filter = { numberOfPurchases: -1 };
const options = {
projection: {
_id: 1,
foodName: 1,
foodImage: 1,
description: 1,
postedDate: 1,
price: 1,
numberOfPurchases: 1,
},
};
const result = await foods_collection
.find(query, options)
.sort(filter)
.limit(6)
.toArray();
res.send(result);
});
// POST :: add new food item into foods collection in database
app.post("/foods", async (req, res) => {
const theFood = req.body;
// console.log(theFood);
const result = await foods_collection.insertOne(theFood);
// console.log(result);
res.send(result);
});
// PATCH :: update the 'numberOfPurchases' property of food items when a user purchases food.
app.patch("/foods", async (req, res) => {
const purchasesInfo = req.body;
const { productId, purchasesQuantity } = purchasesInfo;
// console.log(productId, purchasesQuantity);
const filter = { _id: new ObjectId(productId) };
const document = {
$inc: { numberOfPurchases: purchasesQuantity },
};
const result = await foods_collection.updateOne(filter, document);
res.send(result);
});
// PUT :: update single food data into foods collection in database
app.put("/food/:id", async (req, res) => {
const id = req.params.id;
const getFood = req.body;
const filter = { _id: new ObjectId(id) };
const options = { upsert: true };
const updatedFood = {
$set: {
...getFood,
},
};
const result = await foods_collection.updateOne(
filter,
updatedFood,
options
);
res.send(result);
});
// DELETE :: delete single food data from foods collection in database
app.delete("/foods/:id", async (req, res) => {
const id = req.params.id;
const filter = { _id: new ObjectId(id) };
const result = await foods_collection.deleteOne(filter);
res.send(result);
});
// GET :: get all riviews from review_gallary collection in database
app.get("/reviews", async (req, res) => {
const result = await reviews_collection.find().toArray();
res.send(result);
});
// POST :: add new user review into review gallary collection in database
app.post("/reviews", async (req, res) => {
const newReview = req.body;
// console.log(newReview);
const result = await reviews_collection.insertOne(newReview);
res.send(result);
});
// POST :: add new item or food into purchases collection in database
app.post("/purchases", async (req, res) => {
const newPurchase = req.body;
const result = await purchases_collection.insertOne(newPurchase);
res.send(result);
});
// GET :: get multiple purchased foods from purchases collection in database
app.get("/purchases", verifyToken, async (req, res) => {
// console.log("requested info", req.query);
// console.log("decoded info", req.user);
if (req?.query?.userEmail !== req.user.email) {
return res.status(403).send({ message: "forbidden access" });
}
let query = {};
if (req.query.userEmail) {
query = { "buyerInfo.buyerEmail": req.query.userEmail };
}
const result = await purchases_collection.find(query).toArray();
res.send(result);
});
// DELETE :: delete a single food from purchases food collection in database
app.delete("/purchases/:id", async (req, res) => {
const id = req.params.id;
const quary = { _id: new ObjectId(id) };
const result = await purchases_collection.deleteOne(quary);
res.send(result);
});
// Send a ping to confirm a successful connection
// await client.db("admin").command({ ping: 1 });
console.log(
"Pinged your deployment. You successfully connected to MongoDB!"
);
} finally {
// Ensures that the client will close when you finish/error
// await client.close();
}
}
run().catch(console.dir);
app.get("/", (req, res) => {
res.send("PIQUANT Server is running...");
});
app.listen(port, () => {
console.log(`PIQUANT Server is running on port ${port}`);
});