-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdataService_old.js
More file actions
485 lines (422 loc) · 14 KB
/
dataService_old.js
File metadata and controls
485 lines (422 loc) · 14 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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
const mongoose = require("mongoose");
const Restaurant = require('./models/restaurant');
const Cuisine = require('./models/cuisine');
const Mark = require('./models/mark');
const PriceRange = require('./models/priceRange');
const Review = require('./models/review');
const User = require('./models/user');
const Group = require('./models/group');
module.exports = () => {
return {
// ///// Function Outline!
// functionName: () => {
// return new Promise((resolve, reject) => {
// SchemaName.what()
// .then(data => {
// resolve(data)
// }).catch(err => {
// reject(err)
// });
// });
// },
getRestaurants: () => {
return new Promise((resolve, reject) => {
Restaurant.find()
.then(data => {
console.log('data retrieved?', data)
resolve(data)
}).catch(err => {
console.log('ERROROROOR')
reject(err)
});
});
},
getRestaurantById: (locationId) => {
return new Promise((resolve, reject) => {
// validate location ******ADD ! TO IMPLEMENT******
// if (locationId.match(/^[0-9a-fA-F]{24}$/)) {
// reject('invalid id')
// }
Restaurant.findOne({ locationId })
.then(data => {
if (data) {
console.log('search result: ', data)
resolve(data)
} else reject('no restaurant with specified id')
})
.catch(err => {
console.log('fail')
reject(err)
});
});
},
//check groupid exists first?
//PREVENT ADDING DUPLICATE??
addRestaurant: (restuarantData) => {
return new Promise((resolve, reject) => {
let { groupId, geometry, restaurantName, restaurantLocation, userId } = restuarantData
if (!(groupId || geometry || restaurantName || restaurantLocation || userId)) { // check if group id is valid
reject({"error": "missing fields, need groupId, geometry, restaurantName, restaurantLocation, userId"})
return;
}
if (!mongoose.Types.ObjectId.isValid(groupId) || !mongoose.Types.ObjectId.isValid(userId)) {
reject({"error": "either groupId or userId cannot be converted to valid ObjectId"})
}
console.log(groupId)
console.log('body data: ', restuarantData)
let refId = ''
Mark.create({
locationId: new mongoose.Types.ObjectId(),
groupId,
geometry
}).then(data => {
console.log('returned from mark', data)
refId = data.id // later populated via id!
console.log('ID to use: ', data.locationId)
Restaurant.create({
...restuarantData,
locationId: data.locationId
}).then(data => {
console.log('returned from restaurant: ', data)
// if (groupId) {
Group.findByIdAndUpdate(
groupId,
{ $push: { groupMarks: refId } },//data.locationId
{ runValidators: true }
).then(data => {
console.log('returned from adding marker to group, if null then group d.n.e', data)
}).catch(err => {
console.log('couldnt add marker to group')
reject(err)
})
// } else {
// reject("mark and restuarant, but not added to group")
// return;
// }
console.log('resolving!')
resolve(data)
}).catch(err => {
console.log(4, err)
reject(err)
});
}).catch(err => {
console.log(3)
reject(err)
});
})
},
// delete restaurant and corresponding mark
deleteRestaurantById: (locationId) => {
return new Promise((resolve, reject) => {
let errorMessage = ''
let restaurantDeleted = false
let markDeleted = false
// delete restaurant
Restaurant.deleteOne({ locationId })
.exec()
.then(data => {
console.log("restaraunt deleted count: ", data.deletedCount)
if (data.deletedCount === 1) {
restaurantDeleted = true
}
// delete mark
Mark.deleteOne({ locationId })
.exec()
.then(data => {
console.log('mark deleted count: ', data.deletedCount)
if (data.deletedCount === 1) {
markDeleted = true
if (restaurantDeleted) resolve({'success': 'restuarant and mark deleted'})
///////////////DELETE MARKER OID FROM GROUPMARKERS ARRAY, delete all corresponding reviews////////////
else errorMessage = 'mark deleted, restaurant with specified id does not exist'
} else {
if (restaurantDeleted) errorMessage = 'restuarant deleted, mark with specified id does not exist'
else errorMessage = 'no mark or restaurant with specified id'
}
reject(errorMessage)
})
.catch(err => {
console.log('fail')
reject(err.message)
});
}).catch(err => {
console.log('failed?')
reject(err.message)
});
})
},
updateRestaurantById: (locationId, newData) => {
return new Promise((resolve, reject) => {
console.log('running?')
Restaurant.findOneAndUpdate({ locationId }, newData, {runValidators:true}).then((data) => {
console.log('successfull update, this is old: ', data);
resolve(data)
}).catch(err => {
console.log('problem??', err.message)
reject(err.message)
});
})
},
//get reviews for specific restauarant
getAllReviews: () => {
return new Promise((resolve, reject) => {
Review.find()
.then(data => {
resolve(data)
}).catch(err => {
reject(err)
});
})
},
getReviewsByRestaurant: (reqBody) => {
return new Promise((resolve, reject) => {
let { locationId } = reqBody
if (!locationId) {
reject({"error": "include locationId in body"})
return;
}
Restaurant.findOne({locationId}).populate("restaurantReviews").then(data => {
if (data) {
console.log('restaurantReviews', data.restaurantReviews)
resolve(data)
} else reject({"error": "no restaurant with specified id"})
}).catch(err => {
console.log('error', err)
reject(err)
});
});
},
addReview: (reviewData) => {
return new Promise((resolve, reject) => {
console.log('body data: ', reviewData)
// format creation body first?
// check if provided userId/restaurantId is valid first?
Review.create({
...reviewData
}).then(data => {
console.log('returned from review creation', data, data.id)
Restaurant.findOneAndUpdate(
{ locationId: data.restaurantId },
{ $push: { restaurantReviews: data.id } },//data.locationId
{ runValidators: true }
).then(data => {
console.log('returned from adding review to restaurant', data)
resolve(data)
}).catch(err => {
console.log('couldnt add review to restuarant')
reject(err)
})
}).catch(err => {
reject(err)
});
})
},
updateReviewById: (reviewId, newReview) => {
return new Promise((resolve, reject) => {
// check if restaurant&user id match! then update. otherwise throw error
// Review.pre('validate', function(next) {
// console.log("WOOOOO")
// if (self.isModified('_createdOn')) {
// self.invalidate('_createdOn');
// }
// });
if (!mongoose.Types.ObjectId.isValid(newReview.restaurantId) ||
!mongoose.Types.ObjectId.isValid(newReview.reviewUser.userId)) {
reject("invalid restaurant or user Id")
}
Review.findById(reviewId).then(doc => {
if (!doc) {
reject({"error": "review doesn't exist"}) //TURN INTO 404????????????
} else {
console.log("OLD DOC:", doc)
console.log("NEW DOC:", newReview)
if (!( doc.restaurantId.toString() === newReview.restaurantId ) ||
!( doc.reviewUser.userId.toString() === newReview.reviewUser.userId)) {
reject("cannot update restaurant or user Id")
} else {
doc.reviewContent = newReview.reviewContent
doc.reviewRating = newReview.reviewRating
doc.save().then(data => {
resolve({"success": data})
}).catch(err => {
reject(err)
})
}
}
}).catch(err => reject(err))
// Review.findByIdAndUpdate(reviewId, newReview, {runValidators: true}).then(data => {
// if (data) {
// console.log('review delete results:', data)
// resolve({'success': 'review updated'})
// } else reject('no review with specified id')
// }).catch(err => {
// reject(err)
// })
})
},
deleteReviewById: (id) => {
return new Promise((resolve, reject) => {
Review.findByIdAndDelete(id).then(data => {
if (data) {
console.log('review delete results:', data)
resolve({'success': 'review deleted'})
} else reject('no review with specified id')
}).catch(err => {
console.log('fail')
reject(err.message)
});
})
},
getMarks: (reqQuery) => {
return new Promise((resolve, reject) => {
let { groupId, lat, lng } = reqQuery
if (!groupId) {
reject({"error": "include groupId in query"})
return;
}
if (!lat || !lng) {
//////////////////////////////////////
// WHY NOT MARK.FIND({ groupId })? (add groupid field in addRestaurant in dataService)
Group.findById(groupId).populate("groupMarks").then(data => {
console.log('newdata', data)
// return 404 if null!-todo
console.log('groupmarkers', data.groupMarks)
resolve(data)
}).catch(err => {
console.log('error', err)
reject(err)
});
// Mark.find({ groupId })
// .then(data => {
// resolve(data)
// }).catch(err => {
// console.log('ERROROROOR')
// reject(err)
// });
//////////////////////////////////////////////
} else {
////////////////////////////////////////
coordinates = [
parseFloat(reqQuery.lat),
parseFloat(reqQuery.lng)
]
console.log(coordinates)
Mark.aggregate([
{
$geoNear: {
near: {
type: "Point",
coordinates
},
maxDistance: 100000,
spherical: true,
distanceField: "distance"
}
},
{$match: { groupId: mongoose.Types.ObjectId(groupId) }}
]).then(data => {
console.log('got nearest')
resolve(data)
}).catch(err => {
console.log('error fetching nearest')
reject(err)
})
/////////////////////////////////////////
}
});
},
// configurable maxDistance?
getNearestMarks: (reqQuery) => {
return new Promise((resolve, reject) => {
coordinates = [
parseFloat(reqQuery.lat),
parseFloat(reqQuery.lng)
]
Mark.aggregate().near({
near: {
type: "Point",
coordinates
},
maxDistance: 100000,
spherical: true,
distanceField: "dis"
}).then(data => {
console.log('got nearest')
resolve(data)
}).catch(err => {
console.log('error fetching nearest')
reject(err)
})
})
},
getUsers: () => {
return new Promise((resolve, reject) => {
User.find()
.then(data => {
console.log('data retrieved?', data)
resolve(data)
}).catch(err => {
console.log('ERROROROOR')
reject(err)
});
});
},
addUser: (userData) => {
return new Promise((resolve, reject) => {
console.log('new user data: ', userData)
// format creation body first?
// create. if exists, return error? currently email can't be duplicate
User.create({
...userData
}).then(data => {
console.log('userId: ', data.userId)
resolve(data)
}).catch(err => {
reject(err)
});
})
},
getUserById: (userId) => {
return new Promise((resolve, reject) => {
console.log(userId)
User.findById(userId)
.then(data => {
if (data) resolve(data)
else reject('no user with specified id')
})
.catch(err => {
console.log('fail')
reject(err)
});
});
},
getGroups: () => {
return new Promise((resolve, reject) => {
Group.find().populate("groupMarks")
.then(data => {
console.log('data retrieved?', data)
resolve(data)
}).catch(err => {
console.log('ERROROROOR')
reject(err)
});
});
},
addGroup: (groupData) => {
return new Promise((resolve, reject) => {
console.log('new groupData: ', groupData)
// format creation body first?
// create. if exists, return error?
Group.create({
...groupData
}).then(data => {
console.log('groupId: ', data.groupId)
resolve(data)
}).catch(err => {
console.log(err)
reject(err)
});
})
},
}
}