forked from ironhack-labs/lab-express-spotify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
60 lines (48 loc) · 1.86 KB
/
app.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
require("dotenv").config();
const express = require("express");
const hbs = require("hbs");
const app = express();
app.set("view engine", "hbs");
app.set("views", __dirname + "/views");
app.use(express.static(__dirname + "/public"));
hbs.registerPartials(__dirname + '/views/partials');
// require spotify-web-api-node package here:
const SpotifyWebApi = require("spotify-web-api-node");
// setting the spotify-api goes here:
const spotifyApi = new SpotifyWebApi({
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
});
// Retrieve an access token
(async function configSpotifyApi() {
try{
const result = await spotifyApi.clientCredentialsGrant();
await spotifyApi.setAccessToken(result.body['access_token'])
// ROUTES
app.get("/", (req, res) => {
res.render("home");
});
app.get("/artist-search", async (req, res) => {
const artistSearched = await spotifyApi.searchArtists(req.query.artist)
res.render("artist-search", { artists: artistSearched.body.artists.items })
});
app.get("/albums/:artistId", async (req, res) => {
const artistAlbums = await spotifyApi.getArtistAlbums(req.params.artistId)
const albums = artistAlbums.body.items.map(item => {
item.name = item.name.slice(0,20)
return item
})
res.render('albums', {albums: albums, artist: albums[0].artists[0]})
});
app.get("/albums/tracks/:tracksId", async (req, res) => {
const albumTracks = await spotifyApi.getAlbumTracks(req.params.tracksId)
const tracks = albumTracks.body.items;
res.render("tracks", { tracks });
});
app.listen((process.env.PORT || 3000), () =>
console.log("My Spotify project running on port 3000 🎧 🥁 🎸 🔊")
);
}catch (err) {
console.log("Something went wrong when retrieving an access token", err)
}
})()