forked from bloominstituteoftechnology/webdb-iii-challenge
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
101 lines (88 loc) · 2.35 KB
/
Copy pathserver.js
File metadata and controls
101 lines (88 loc) · 2.35 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
const express = require('express');
const helmet = require('helmet');
const server = express();
const knexConfig = require('./data/dbConfig');
const db = knexConfig;
server.use(helmet());
server.use(express.json());
server.get('/', (req, res) => {
res.send('home page');
});
server.get('/api/cohorts', async (req, res) => {
try {
const cohorts = await db('cohorts');
res.status(200).json(cohorts);
} catch (error) {
res.status(500).json(error);
}
});
server.get('/api/cohorts/:id', async (req, res) => {
try {
const cohort = await db('cohorts')
.where({ id: req.params.id })
.first();
res.status(200).json(cohort);
} catch (error) {
res.status(500).json(error);
}
});
server.post('/api/cohorts', async (req, res) => {
try {
const [id] = await db('cohorts').insert(req.body);
const newCohort = await db('cohorts')
.where({ id })
.first();
res.status(201).json(newCohort);
} catch (error) {
res.status(500).json({ message: error });
}
});
server.put('/api/cohorts/:id', async (req, res) => {
try {
const count = await db('cohorts')
.where({ id: req.params.id })
.update(req.body);
if (count) {
const updatedCohort = await db('cohorts')
.where({ id: req.params.id })
.first();
res.status(200).json(updatedCohort);
} else {
res.status(404).json({
message: 'Cohort not found, make sure you have the right entry!',
});
}
} catch (error) {
res.status(500).json({ message: error });
}
});
server.delete('/api/cohorts/:id', async (req, res) => {
try {
const count = await db('cohorts')
.where({ id: req.params.id })
.del();
if (count) {
res.status(204).end();
} else {
res.status(404).json({
message: 'Cohort not found, make sure you have the right entry!',
});
}
} catch (error) {
res.status(500).json({ message: error });
}
});
// Student routes
server.get('/api/cohorts/:id/students', async (req, res) => {
try {
const cohort = await db
.select('cohorts.name as Cohort', 'students.name as Students')
.from('cohorts')
.innerJoin('students', 'cohorts.id', 'students.cohort_id')
.where('cohorts.id', req.params.id);
res.status(200).json(cohort);
} catch (error) {
res.status(500).json(error);
}
});
module.exports = server;