-
Notifications
You must be signed in to change notification settings - Fork 0
/
searches-router.js
103 lines (93 loc) · 2.53 KB
/
searches-router.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
'use strict';
const express = require('express');
const mongoose = require('mongoose');
const passport = require('passport');
const router = express.Router();
const { jwtStrategy } = require('./auth/strategies')
router.use(express.json());
router.use(express.static('public/searches'));
mongoose.Promise = global.Promise;
const { Users, PastSearches } = require('./model');
passport.use(jwtStrategy);
const jwtAuth = passport.authenticate('jwt', { session: false });
router.get('/', (req, res) => {
console.log('Retrieving Searches');
PastSearches.find()
.then(searches => {
res.json({
searches: searches.map(
(search) => search.serialize())
});
})
.catch(err => {
console.error(err);
res.status(500).json({ message: 'Internal server error' });
});
});
router.get('/currentuser', jwtAuth, (req, res) => {
let userObjectId = mongoose.Types.ObjectId(req.user.id);
PastSearches
.find({user: userObjectId})
.then(function(searches) {
return res.json({
searches: searches.map(
(search) => search.serialize())
});
})
.catch(err => {
console.error(err);
res.status(500).json({ error: 'something went horribly awry' });
});
});
router.post('/', (req, res) => {
console.log('posting new past search');
const requiredFields = ['username', 'music_title', 'IMSLP_links', 'creation'];
requiredFields.forEach(field => {
if (!(field in req.body)) {
const message = `Missing ${field} in request body`;
console.error(message);
return res.status(400).send(message);
}
});
Users
.find( { username: req.body.username } )
.then(users => {
if (users) {
PastSearches
.create({
user: users[0]._id,
music_title: req.body.music_title,
IMSLP_links: req.body.IMSLP_links,
creation: req.body.creation
})
.then(function(search) {
PastSearches.find({_id: search._id}, function(err, results) {
res.status(201).json(results[0].serialize());
})
})
.catch(err => {
console.error(err);
res.status(500).json({ error: 'Something went wrong '});
});
}
else {
const message = 'User not found.';
console.error(message);
return res.status(400).send(message);
}
})
.catch(err => {
console.error(err);
res.status(500).json({ error: 'Something went horribly awry' });
});
});
router.delete('/:id', (req, res) => {
console.log('deleting past search');
PastSearches
.findByIdAndRemove(req.params.id)
.then(() => {
console.log(`Deleted past search with id ${req.params.id}`);
res.status(204).end();
});
});
module.exports = router;