-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
268 lines (211 loc) · 6.37 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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
const express = require('express')
const cors = require('cors')
var jwt = require('jsonwebtoken')
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb')
const nodemailer = require("nodemailer");
require('dotenv').config()
const stripe = require('stripe')(process.env.STRIPE_SCRET_KEY);
const app = express()
const port = process.env.PORT || 8080
// middlewares
app.use(cors())
app.use(express.json())
// Nodemail
const sendMail = (bookingData, email) => {
console.log(bookingData, email)
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.NODEMAILER,
pass: process.env.PASS
}
});
const mailOptions = {
from: process.env.NODEMAILER,
to: email,
subject: bookingData?.subject,
html: `<p>${bookingData?.messages}</p>
<p>Price: ${bookingData?.price}</p>
<p>TransactionId: ${bookingData?.transactionId}</p>
<p>Location: ${bookingData?.home?.location}</p>
<p>From: ${bookingData?.home?.from}</p>
<p>To: ${bookingData?.home?.to}</p>
<p style={margin-bottom: 10px}>Host Email: ${bookingData?.hostEmail}</p>
<img src=${bookingData?.home?.image}/>
`
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
// do something useful
}
});
}
function verifyJWT(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader) {
return res.status(401).send('Unauthorized access')
}
const token = authHeader.split(' ')[1]
jwt.verify(token, process.env.ACCESS_TOKEN, function (err, decoded) {
if (err) {
return res.status(403).send({ message: 'Forbidden Access' })
}
req.decoded = decoded;
next()
})
}
// Database Connection
const uri = process.env.RB_URI
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverApi: ServerApiVersion.v1,
})
async function run() {
try {
const homesCollection = client.db('roombooking').collection('homes');
const userCollections = client.db('roombooking').collection('users');
const bookingCollections = client.db('roombooking').collection('bookings');
const paymentCollections = client.db('roombooking').collection('payments');
// Save user email and generate JWT
app.put('/user/:email', verifyJWT, async (req, res) => {
const email = req.params.email;
const user = req.body;
const filter = { email: email };
const options = { upsert: true };
const updateDoc = {
$set: user
}
const result = await userCollections.updateOne(filter, updateDoc, options);
// JWT
const token = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, {
expiresIn: '1d'
})
res.send({ result, token })
})
// get user Role
app.get('/user/:email', async (req, res) => {
const email = req.params.email;
const query = { email: email };
const user = await userCollections.findOne(query)
res.send(user)
})
// get all user Role
app.get('/users', async (req, res) => {
const users = await userCollections.find().toArray()
res.send(users)
})
// Services Post
app.post('/services', async (req, res) => {
const service = req.body;
const result = await homesCollection.insertOne(service)
res.send(result)
})
// Services Post
app.get('/services', async (req, res) => {
const query = {}
const email = req.params.email;
if (email) {
query = {
host: {
email: email
}
}
}
const result = await homesCollection.find(query).toArray()
res.send(result)
})
// Update service
app.put('/service', async (req, res) => {
const service = req.body;
console.log(service)
const filter = {}
const options = { upsert: true };
const updateDoc = {
$set: service
}
const result = await homesCollection.updateOne(filter, updateDoc, options);
res.send(result)
})
// Single Service
app.get('/service/:id', async (req, res) => {
const id = req.params.id;
const query = { _id: ObjectId(id) }
const result = await homesCollection.findOne(query);
res.send(result)
})
// Services Post
app.delete('/services/:id', async (req, res) => {
const id = req.params.id;
const filter = { _id: ObjectId(id) }
const result = await homesCollection.deleteOne(filter)
console.log(result)
res.send(result)
})
// Serach Result
app.get('/serach-result', async (req, res) => {
const query = {}
const location = req.query.location;
if (location) {
query.location = location
} else {
res.send({ message: `No result found` })
};
const cursor = homesCollection.find(query)
const result = await cursor.toArray()
res.send(result)
})
// Booking data post method in database
app.post('/bookings', async (req, res) => {
const bookingData = req.body;
const result = await bookingCollections.insertOne(bookingData);
sendMail(
{
subject: `Booking successful`,
messages: `Booking id: ${result.insertedId}`,
...bookingData
},
bookingData?.guestEmail)
res.send({ transactionId: bookingData.transactionId })
console.log(result)
})
// Get Booking data from Database
app.get('/bookings', async (req, res) => {
let query = {};
const email = req.query.email;
if (email) {
query = {
guestEmail: email
}
}
const result = await bookingCollections.find(query).toArray()
res.send(result)
})
// Payment
app.post('/create-payment', async (req, res) => {
const price = req.body.price;
const amount = parseFloat(price * 100);
const paymentIntent = await stripe.paymentIntents.create({
amount: amount,
currency: 'usd',
payment_method_types: [
"card"
],
})
res.send({
clientSecret: paymentIntent.client_secret,
});
})
} finally {
}
}
run().catch(err => console.error(err))
app.get('/', (req, res) => {
res.send('Server is running...')
})
app.listen(port, () => {
console.log(`Server is running...on ${port}`)
})