-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
406 lines (351 loc) · 9.26 KB
/
Copy pathserver.js
File metadata and controls
406 lines (351 loc) · 9.26 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
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
import express from "express"
import cors from "cors"
import mongoose from "mongoose"
import listEndpoints from 'express-list-endpoints'
import crypto from 'crypto'
import bcrypt from 'bcrypt-nodejs'
import restaurants from "./data/restaurants.json"
const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/project-mongo"
mongoose.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true })
mongoose.Promise = Promise
const RestaurantSchema = new mongoose.Schema({
id: String,
name: String,
image_URL: String,
description: String,
address: String,
opening_hours_mon: String,
opening_hours_tue: String,
opening_hours_thur: String,
opening_hours_wed: String,
opening_hours_fri: String,
opening_hours_sat: String,
opening_hours_sun: String,
meals: Array,
budget: Array,
type_of_food: Array,
dogfriendly: Boolean,
portion_size: Array,
target_audience: Array,
outdoor_area: Boolean,
restaurant_focus: Array,
website: String
})
const Restaurant = mongoose.model('Restaurant', RestaurantSchema)
const UserSchema = new mongoose.Schema({
username: {
type: String,
unique: true,
minlength: 3,
maxlength: 20,
required: true
},
email: {
type: String,
required: true,
unique: true,
validate: {
validator: (value) => {
return /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(value)
}
}
},
password: {
type: String,
minlength: 8,
required: true
},
accessToken: {
type: String,
default: () => crypto.randomBytes(128).toString('hex')
},
fullName: {
type: String,
unique: false
},
phone: {
type: Number,
unique: false
},
bio: {
type: String,
unique: false
}
})
const User = mongoose.model('User', UserSchema)
const ReviewSchema = new mongoose.Schema({
review: {
type: String,
minlength: 5,
maxlength: 140,
required: true,
trim: true
},
like: {
type: Number,
default: 0
},
author: {
type: String,
required: true,
trim: true
},
restaurant: {
type: String,
required: true,
trim: true
},
createdAt: {
type: Date,
default: () => new Date()
},
})
const Review = mongoose.model('Review', ReviewSchema)
const port = process.env.PORT || 8080
const app = express()
app.use(cors())
app.use(express.json())
//----------------------IF ENABLED TO REACH DATABASE---------------------//
app.use((req, res, next) => {
if (mongoose.connection.readyState === 1) {
next()
} else {
res.status(503).json({ error: 'Service unavailable' })
}
})
//-----LOOKS UP THE USER BASED ON ACCESSTOKEN STORED IN HEADER, THEN CALLING NEXT-----//
const authenticateUser = async (req, res, next) => {
try {
const user = await User.findOne({
accessToken: req.header('Authorization')})
if (user) {
req.user = user
next()
} else {
res.status(401).json({ response: 'Please, log in', success: false })
}
} catch (error) {
res.status(400).json({ response: 'Invalid request', error })
}
}
//---------------------------STARTPAGE---------------------------//
app.get("/", (req, res) => {
res.send(listEndpoints(app))
})
//-------------------------GET ALL RESTAURANTS-------------------------//
app.get('/restaurants', authenticateUser)
app.get('/restaurants', (req, res) => {
try{
res.status(200).json({
response: restaurants,
success: true
})
} catch (error) {
res.status(400).json({
response: error,
success: false })
}
})
//----------------------GET A SPECIFIC RESTAURANT--------------------//
app.get('/restaurants/:id', authenticateUser)
app.get('/restaurants/:id', async (req, res) => {
const { id } = req.params
try{
const restaurant = await Restaurant.findOne({ id: id })
if(restaurant){
res.status(200).json({
response: restaurant,
success: true
})
} else {
res.status(404).json({
response: 'No data found',
success: false
})
}
} catch (error) {
res.status(400).json({
response: error,
success: false })
}
})
//---------------------------PROFILE PROTECTED ENDPOINT---------------------------//
app.get('/profile/:id', authenticateUser)
app.get('/profile/:id', async (req, res) => {
const { id } = req.params
try {
const user = await User.findById(id)
if (user) {
res.status(201).json({
email: user.email,
fullName: user.fullName,
profileImage: user.profileImage,
password: user.password,
fullName: user.fullName,
phone: user.phone,
bio: user.bio})
} else {
res.status(404).json({
message: 'Could not find profile information',
success: false })
}
} catch (error) {
res.status(400).json({
message: error,
success: false})
}
})
//--------------------------- PROFILE SETTINGS ENDPOINT---------------------------//
app.patch('/profile/:id', authenticateUser)
app.patch('/profile/:id', async (req, res) => {
const { id } = req.params
try {
const updateUser = await User.findByIdAndUpdate(id, req.body, { new: true})
if (updateUser) {
res.status(200).json({ success: true, response: updateUser })
} else {
res.status(404).json({ success: false, response: 'Not found' })
}
} catch (error) {
res.status(400).json({ response: 'Invalid request', error})
}
})
//---------------------------SIGN UP ENDPOINT---------------------------//
app.post('/signup', async (req, res) => {
const { username, password, email } = req.body
try {
const salt = bcrypt.genSaltSync()
if (password.length < 8) {
res.status(400).json({
response: "Your password must be at least 8 characters long",
success: false
})
} else {
const newUser = await new User({
username,
email,
password: bcrypt.hashSync(password, salt),
}).save()
res.status(201).json({
response: {
userId: newUser._id,
email: newUser.email,
username: newUser.username,
accessToken: newUser.accessToken,
fullName: newUser.fullName,
phone: newUser.phone,
bio: newUser.bio
},
success: true,
})
}
} catch (error) {
res.status(400).json({
response: error,
success: false
})
}
})
//---------------------------LOGIN ENDPOINT---------------------------//
app.post('/login', async (req, res) => {
const { username, password } = req.body
try {
const user = await User.findOne({ username })
if (user && bcrypt.compareSync(password, user.password)) {
res.status(200).json({
response: {
userId: user._id,
username: user.username,
accessToken: user.accessToken,
fullName: user.fullName,
phone: user.phone,
bio: user.bio
},
success: true,
})
} else {
if (username === '') {
res.status(404).json({
message: 'Login failed: fill in username',
response: error,
success: false,
})
} else if (password === '') {
res.status(404).json({
message: 'Login failed: fill in password',
response: error,
success: false,
})
} else {
res.status(404).json({
message: 'Login failed: wrong username or password',
response: error,
success: false,
})
}
}
} catch (error) {
res.status(400).json({
message: 'Invalid entry',
response: error,
success: false,
})
}
})
//------- POST REVIEW -------//
app.post('/reviews', authenticateUser, async (req, res) => {
const { author } = req.body
const { review } = req.body
const { restaurant } = req.body
try {
const newReview = await new Review({
review: review,
author: author,
restaurant: restaurant
}).save()
if(newReview){
res.status(201).json({
response: {
_id: newReview._id,
review: newReview.review,
like: newReview.like,
author: newReview.author,
createdAt: newReview.createdAt,
restaurant: newReview.restaurant
},
success: true
})
}else {
res.status(404).json({
response: 'Could not post review',
success: false
})
}
} catch (error) {
res.status(400).json({
response: error,
success: false
})
}
})
///------LIST OF REVIEWS----------------///
app.get('/reviews', authenticateUser, async (req,res) => {
try {
const allReviews = await Review.find({}).sort({createdAt: 'desc'}).limit(20)
if (allReviews) {
res.status(200).json(allReviews)
} else {
res.status(404).json({
response: error,
success: false})
}
} catch (error) {
res.status(400).json({
response: error,
success: false})
}
})
//-------------------------START SERVER-------------------------//
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`)
})