forked from Josephhaefling/ArtisTry-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
82 lines (62 loc) · 2.28 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
const cors = require('cors');
const request = require('request')
const fetch = require("node-fetch");
const express = require('express');
const app = express();
const shortid = require('shortid');
fetch(request, {mode: 'cors'});
app.use(express.json());
app.set('port', process.env.PORT || 3001);
app.use(cors());
app.use(express.static("build"))
app.locals.title = 'ArtisTry Backend';
app.get('/', (request, response) => {
response.send('ArtisTry Backend');
});
app.locals.favorites = []
app.get('/api/v1/favorites', (request, response) => {
const favorites = app.locals.favorites;
if(!favorites) {
return response.sendStatus(404)
}
response.json({ favorites });
});
app.post('/api/v1/favorites', (request, response) => {
const id = shortid.generate();
const favorite = request.body;
for (let requiredParameter of [
'title',
'contentId',
'artistContentId',
'artistName',
'completitionYear',
'yearAsString',
'width',
'image',
'height',
'name'
]) {
if (!favorite[requiredParameter]) {
return response
.status(422)
.send({ error: `Expected format: { artist: <String>, title: <String> }. You're missing a "${requiredParameter}" property.` });
}
}
const { title, contentId, artistContentId, artistName, completitionYear, yearAsString, width, image, height, name } = favorite;
app.locals.favorites.push({ title, contentId, artistContentId, artistContentId, artistName, completitionYear, yearAsString, width, image, height, name });
response.status(201).json({ artistName, title});
});
app.delete('/api/v1/favorites/:contentId', (request, response) => {
const { contentId } = request.params;
const parsedId = parseInt(contentId);
const match = app.locals.favorites.find(painting => parseInt(painting.contentId) === parsedId);
if (!match) {
return response.status(404).json({ error: `No painting found with an id of ${contentId}.` })
}
const updatedPaintings = app.locals.favorites.filter(painting => parseInt(painting.contentId) !== parsedId);
app.locals.favorites = updatedPaintings;
return response.status(202).json(app.locals.favorites)
});
app.listen(app.get('port'), () => {
console.log(`${app.locals.title} is running on http://localhost:${app.get('port')}.`);
});