-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspotify-favorite-genres-view.js
59 lines (50 loc) · 1.22 KB
/
spotify-favorite-genres-view.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
"use latest";
var { MongoClient } = require('mongodb');
var handlebars = require('handlebars');
var View = `
<html>
<head>
<title>Favorite genres</title>
</head>
<body>
{{#if genres.length}}
Favorite genres:
<ul>
{{#each genres}}
<li>{{genre}}: {{count}}</li>
{{/each}}
</ul>
{{else}}
<h1>No genres found. Go listen to some music!(</h1>
{{/if}}
</body>
</html>
`;
function getGenres(mongoUrl, callback) {
MongoClient.connect(mongoUrl, (error, database) => {
if(error) callback(error, null);
database
.collection('genres')
.find()
.toArray( (error, genres) => {
if(error) callback(error, null);
callback(null, genres);
});
});
}
function buildView(genres) {
const view_ctx = {
genres: genres.sort( (genre1, genre2) => {
return genre2.count - genre1.count;
})
};
const template = handlebars.compile(View);
return template(view_ctx);
}
return (context, request, response) => {
getGenres(context.data.MONGO_URL, (error, genres) => {
if(error) return response.end(error);
response.writeHead(200, { 'Content-Type': 'text/html' });
response.end(buildView(genres));
});
};