-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
83 lines (67 loc) · 2.61 KB
/
server.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
/* eslint no-console: 0 */
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const app = express();
const enviroment = process.env.NODE_ENV || 'development';
const configuration = require('./knexfile')[enviroment];
const database = require('knex')(configuration);
app.set('port', process.env.PORT || 3000);
app.locals.title = 'Garage Bin';
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, '/public')));
app.get('/api/v1/items', (request, response) => {
database('items').select()
.then((items) => {
if (!items) {
return response.status(404).json({ error: 'No items exist in garage' });
}
return response.status(200).json({ items });
})
.catch((error) => {
throw error;
});
});
app.get('/api/v1/items/:id', (request, response) => {
const { id } = request.params;
database('items').where('id', id).select()
.then((item) => {
if (!item.length) {
return response.status(404).json({ error: `No item exists in garage with 'id' of '${id}' ` });
}
return response.status(200).json({ item: item[0] });
});
});
app.post('/api/v1/items', (request, response) => {
const { name, reason, cleanliness } = request.body;
const item = { name, reason, cleanliness };
for (const requiredParameter of ['name', 'reason', 'cleanliness']) {
if (!request.body[requiredParameter]) {
return response.statusps(422).json({ error: `You are missing the '${requiredParameter}' property` });
}
}
database('items').insert(item, 'id')
.then(postedItem => response.status(201).json({ itemId: postedItem[0] }))
.catch(error => response.json({ error }));
});
app.patch('/api/v1/items/:id', (request, response) => {
const { id } = request.params;
const { name, reason, cleanliness } = request.body;
const body = { name, reason, cleanliness };
database('items').where('id', id).update(body, '*')
.then((item) => {
if (!item.length) {
return response.status(404).json({ error: `Could not find an item in garage with 'id' ${id}` });
}
return response.status(202).json({ item: item[0] });
})
.catch(error => response.status(500).json({ error }));
});
app.use((request, response) => response.status(404).send("404: Sorry can't find that!"));
app.use((error, request, response) => {
console.error(error.stack);
return response.status(500).send('Something broke!');
});
app.listen(app.get('port'), () => console.log(`${app.locals.title} is running on ${app.get('port')}`));
module.exports = app;