-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
71 lines (56 loc) · 1.49 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
const express = require('express');
const app = express();
app.use(express.json());
let playlist = [
]
const getPlaylist = () => {
return playlist;
}
const addSong = (title, artists) => {
let song = {
songId: generateSongId(),
title,
artists,
playCount: 0
}
playlist.push(song);
return song;
}
const generateSongId = () => {
const randomId = Math.random().toString(10).substring(2, 6);
return `song${randomId}`;
}
const getSong = (songId) => {
const song = playlist.find(s => s.songId === songId);
return song;
}
const sortedPlaylist = () => {
const sorted = [...playlist].sort((a, b) => b.playCount - a.playCount);
return sorted;
}
app.get('/playlist', (req, res) => {
const playlist = getPlaylist();
res.status(200).json({playlist});
})
app.post('/playlist', (req, res) => {
const {title, artists} = req.body;
const song = addSong({title, artists});
res.status(201).json({message: "lagu berhasil ditambah"});
})
app.put('/playlist/:songId', (req, res) => {
const songId = req.params.songId;
const song = getSong(songId);
if(song){
song.playCount++;
res.status(200).json({song});
}else{
res.status(404).json({message: "lagu tidak ditemukan"});
}
})
app.get('/playlist/sorted', (req, res) => {
const sortedPlaylist = sortedPlaylist();
res.status(200).json({sortedPlaylist});
})
app.listen(3000, () => {
console.log('app: http://localhost:3000');
})