-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·102 lines (84 loc) · 3.61 KB
/
index.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
const sqlite = require('sqlite'),
Sequelize = require('sequelize'),
request = require('request'),
express = require('express'),
app = express();
const { PORT=3000, NODE_ENV='development', DB_PATH='./db/database.db' } = process.env;
// START SERVER
Promise.resolve()
.then(() => app.listen(PORT, () => console.log(`App listening on port ${PORT}`)))
.then(() => sqlite.open('./db/database.db'))
.catch((err) => { if (NODE_ENV === 'development') console.error(err.stack); });
// ROUTES
app.get('/films/:id/recommendations', getFilmRecommendations);
app.get('*', (req, res) => res.status(404).send({ message: "Unavaiable route" }));
function dateRange(date) {
let date1,
date2,
splitDate = date.split('-'),
year = +splitDate[0];
date1 = (year - 15).toString() + '-' + splitDate.slice(1).join('-');
date2 = (year + 15).toString() + '-' + splitDate.slice(1).join('-');
return [date1, date2];
}
function filmAverageRating(reviews) {
let ratingSum = 0;
reviews.forEach(review => ratingSum += review.rating);
return (ratingSum / reviews.length).toFixed(2);
}
// ROUTE HANDLER
function getFilmRecommendations(req, res) {
let filmId = +req.params.id,
limit = +req.query.limit || 10,
offset = req.query.offset === undefined ? 0 : +req.query.offset;
if (typeof filmId === 'number') {
sqlite.get('SELECT * FROM films WHERE id = ?', filmId)
.then(film => {
let dates = dateRange(film.release_date);
sqlite.all('SELECT films.id, films.title, films.release_date, name AS genre FROM films, genres WHERE genre_id = ? AND release_date BETWEEN ? AND ? AND genres.id = films.genre_id', film.genre_id, dates[0], dates[1])
.then(foundFilms => {
let filmIds = [],
films = {};
foundFilms.forEach(f => {
filmIds.push(f.id);
films[f.id] = f;
});
request(`http://credentials-api.generalassemb.ly/4576f55f-c427-4cfc-a11c-5bfe914ca6c1?films=${filmIds.join(',')}`, function (error, response, body) {
let reviews = JSON.parse(body).filter(film =>
film.reviews.length > 4 && filmAverageRating(film.reviews) >= 4
),
recommendations = [];
if (offset > 0) {
reviews = reviews.slice(offset);
}
reviews = reviews.slice(0, limit);
reviews.forEach(review => {
let recommend = {
id: review.film_id,
title: films[review.film_id].title,
releaseDate: films[review.film_id].release_date,
genre: films[review.film_id].genre,
averageRating: filmAverageRating(review.reviews),
reviews: review.reviews.length
};
recommendations.push(recommend);
});
res.setHeader('Content-Type', 'application/json');
res.status(200).send(JSON.stringify({
recommendations: recommendations,
meta: {
limit: limit,
offset: offset
}
}));
})
})
.catch(err => res.status(422).send({ message: 'Unprocessable Entity' }));
})
.catch(err => res.status(422).send({ message: 'Unprocessable Entity' }));
}
else {
res.status(500).send({ message: 'Not a film' });
}
}
module.exports = app;