-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPI.js
More file actions
71 lines (62 loc) · 1.91 KB
/
API.js
File metadata and controls
71 lines (62 loc) · 1.91 KB
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();
const bodyParser = require('body-parser');
var fs = require("fs");
const PORT = process.env.PORT || 4001;
app.use(express.static('public'));
app.use(bodyParser.json());
const { getId, addSong, finished } = require('./APIfunc');
//stored songs
let songs = require('./songs.json');
//get all songs
app.get('/songs', (req, res) => {
res.send(songs);
});
//get a single song by id
app.get('/songs/:id', (req, res) => {
const foundSong = getId(req.params.id, songs);
if (foundSong) {
res.send(songs[req.params.id]);
} else {
res.status(404).send('song does not exist');
}
});
//add song to the list
app.post('/songs/:song', (req, res) => {
const newSong = addSong(req.params.song, songs);
if (newSong) {
res.status(201).send(newSong);
var data = JSON.stringify(songs, null, 2);
fs.writeFile('songs.json',data,finished);
} else {
res.status(400).send('cannot create');
}
});
//update a song
app.put('/songs/:id/:song', (req, res) => {
let getIndex = getId(req.params.id, songs);
if (getIndex) {
songs[req.params.id] = {"song" : req.params.song};
res.send(songs);
var data = JSON.stringify(songs, null, 2);
fs.writeFile('songs.json',data,finished);
}
else {
res.status(404).send('song does not exist');
}
});
//delete a song by id
app.delete('/songs/:id', (req, res) => {
const newidx = getId(req.params.id, songs);
if (newidx) {
delete(songs[req.params.id]);
res.status(204).send('deleted');
var data = JSON.stringify(songs, null, 2);
fs.writeFile('songs.json',data,finished);
} else {
res.status(404).send('song does not exist');
}
});
app.listen(PORT, () => {
console.log(`Server is listening on ${PORT}`);
});