-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
222 lines (198 loc) · 6.76 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
const express = require("express");
const cors = require("cors");
const { MongoClient, ServerApiVersion, ObjectId } = require("mongodb");
require("dotenv").config();
const jwt = require("jsonwebtoken");
const cookieParser = require("cookie-parser");
const app = express();
const port = process.env.PORT || 5000;
const corsOptions = {
origin: [
"http://localhost:5173",
"https://auto-e-librarian.web.app",
"https://auto-e-librarian.firebaseapp.com",
],
credentials: true,
// optionSuccessStatus: 200,
};
// Middleware
app.use(express.json());
app.use(cors(corsOptions));
app.use(cookieParser());
// jwt middleware
const verifyJWToken = (req, res, next) => {
const token = req.cookies?.token;
if (!token) return res.status(401).send({ message: "unauthorized access" });
if (token) {
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
if (err) {
console.error(err);
return res.status(401).send({ message: "unauthorized access" });
}
req.user = decoded;
next();
});
}
};
app.get("/", (req, res) => {
res.send("Welcome to Auto Librarian, a LearnEdge e-Library!");
});
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}@cluster0.jd9hrzt.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 cookieOptions = {
httpOnly: true,
sameSite: process.env.NODE_ENV === "production" ? "none" : "strict",
secure: process.env.NODE_ENV === "production",
// sameSite: "none",
// secure: true,
};
const run = async () => {
try {
// Connect the client to the server (optional starting in v4.7)
// await client.connect();
// Create database and collection as table
const booksCollection = client.db("AutoLibrarianDB").collection("books");
const bookCategories = client
.db("AutoLibrarianDB")
.collection("bookCategories");
const borrowBooks = client.db("AutoLibrarianDB").collection("borrowBooks");
app.post("/jwt", async (req, res) => {
const user = req.body;
const token = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, {
expiresIn: "5h",
});
// res.send({ token });
res.cookie("token", token, cookieOptions).send({ success: true });
});
app.post("/logout", async (req, res) => {
// const user = req.body;
// console.log("Logging out", user);
res
.clearCookie("token", { ...cookieOptions, maxAge: 0 })
.send({ success: true });
});
app.get("/books", async (req, res) => {
const cursor = booksCollection.find();
const result = await cursor.toArray();
res.send(result);
});
app.get("/books/:id", async (req, res) => {
const id = req.params.id;
// console.log("Single id: ", id);
const query = { _id: new ObjectId(id) };
const book = await booksCollection.findOne(query);
res.send(book);
});
app.get("/book-categories", async (req, res) => {
const cursor = bookCategories.find();
const result = await cursor.toArray();
res.send(result);
});
// Get all the Borrowed books
// app.get("/borrow-books", verifyJWToken, async (req, res) => {
// const cursor = borrowBooks.find();
// const result = await cursor.toArray();
// res.send(result);
// });
app.get("/borrowed-books/:email", verifyJWToken, async (req, res) => {
// console.log("cookie", req.cookies);
const tokenEmail = req.user.email;
const email = req.params.email;
if (tokenEmail !== email) {
return res.status(403).send({ message: "forbidden access" });
}
const query = { email };
const result = await borrowBooks.find(query).toArray();
res.send(result);
});
app.patch("/borrow-book/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const updateDoc = {
$inc: { quantity: -1 },
};
const result = await booksCollection.updateOne(query, updateDoc);
res.send(result);
});
app.patch("/return-book/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const updateDoc = {
$inc: { quantity: 1 },
};
const result = await booksCollection.updateOne(query, updateDoc);
res.send(result);
});
app.get("/books", async (req, res) => {
const { category } = req.query;
const filter = category ? { category } : {};
const books = await booksCollection.find(filter).toArray();
res.send(books);
});
app.post("/books", verifyJWToken, async (req, res) => {
const newBook = req.body; // get new item from client site
// console.log("New Book", newBook);
// insertOne item and send to database
const result = await booksCollection.insertOne(newBook);
res.send(result);
});
app.post("/borrow-books", async (req, res) => {
const borrowBook = req.body; // get borrow item from client site
// console.log("Borrow Book", borrowBook);
// insertOne item and send to database
const result = await borrowBooks.insertOne(borrowBook);
res.send(result);
});
app.put("/books/:id", async (req, res) => {
const id = req.params.id;
const book = req.body;
const filter = { _id: new ObjectId(id) };
const options = { upsert: true };
const updateBook = {
$set: {
...book,
},
};
const result = await booksCollection.updateOne(
filter,
updateBook,
options
);
res.send(result);
});
app.delete("/books/:id", async (req, res) => {
const id = req.params.id;
// console.log("Delete from database", id);
const query = { _id: new ObjectId(id) };
const result = await booksCollection.deleteOne(query);
res.send(result);
});
app.delete("/borrowed-books/:id", async (req, res) => {
const id = req.params.id;
// console.log("Delete from database", id);
// const query = { _id: new ObjectId(id) };
const query = { id };
const result = await borrowBooks.deleteOne(query);
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.listen(port, () => {
// console.log(`Auto Librarian server running on port ${port}!`);
});