-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
52 lines (42 loc) · 1.38 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
var unirest = require('unirest');
var express = require('express');
var events = require('events');
var getFromApi = function(endpoint, args) {
var emitter = new events.EventEmitter();
unirest.get('https://api.spotify.com/v1/'+endpoint)
.qs(args)
.end(function(response) {
if(response.ok) emitter.emit('end', response.body);
else emitter.emit('error', response.code);
});
return emitter;
};
var app = express();
app.use(express.static('public'));
app.get('/search/:name', function(req, res) {
var searchReq = getFromApi('search', {
q: req.params.name,
limit: 1,
type: 'artist'
});
searchReq.on('end', function(item) {
var artist = item.artists.items[0];
// console.log('artist: ', artist);
searchReq.emit('getRelatedArtists', artist);
// res.json(artist);
});
searchReq.on('error', function(code) {
res.sendStatus(code);
});
searchReq.on('getRelatedArtists', function(artist) {
var relatedArtists = getFromApi('artists/'+artist.id+'/related-artists');
relatedArtists.on('end', function(list) {
artist.related = list.artists;
res.json(artist);
});
relatedArtists.on('error', function(code) {
res.sendStatus(code);
});
});
});
app.listen(8080);