-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathserver.js
More file actions
46 lines (40 loc) · 1.06 KB
/
server.js
File metadata and controls
46 lines (40 loc) · 1.06 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
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser')
const app = express();
app.use(cors());
app.use(bodyParser.json());
let { data } = require('./data');
const getBookAuthors = book => {
// book.authorId, book.authorIds
const authorIds = book.authorId ? [book.authorId] : book.authorIds || [];
return authorIds.map(authorId =>
Object.assign({}, { id: authorId }, data.authors[authorId])
);
};
app.get('/api/books', (req, res) => {
res.send(data.books.map(book => {
return Object.assign({}, book, {
authors: getBookAuthors(book)
});
}));
});
app.post('/api/books', (req, res) => {
const newBook = {
id: Date.now(),
title: req.body.title,
price: req.body.price,
authors: []
};
data.books.push(newBook);
res.send(newBook);
});
app.delete('/api/books/:bookId', (req, res) => {
data.books = data.books.filter(book =>
book.id !== Number(req.params.bookId)
);
res.send({ deleted: true });
});
app.listen(8000, () => {
console.log('API server is at port 8000');
})