-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
89 lines (63 loc) · 1.91 KB
/
index.js
File metadata and controls
89 lines (63 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());
app.use(express.static('public'));
const books = [
{ id: 1, title: 'The Alchemist', author: 'Paulo Coelho', year: 1988 },
{ id: 2, title: 'Atomic Habits', author: 'James Clear', year: 2018 },
{ id: 3, title: 'Clean Code', author: 'Robert C. Martin', year: 2008 }
];
app.get('/', (req, res) => {
res.send('Hello, Book API is running!');
});
app.get('/books', (req, res) => {
res.json(books);
});
app.get('/books/:id', (req, res) => {
const bookId = parseInt(req.params.id);
const book = books.find(b => b.id === bookId);
if (!book) {
return res.status(404).json({ error: 'Book not found' });
}
res.json(book);
});
app.post('/books', (req, res) => {
console.log('Request body:', req.body);
const { title, author, year } = req.body;
if (!title || !author || !year) {
return res.status(400).json({ error: 'All fields are required' });
}
const newBook = {
id: books.length + 1,
title,
author,
year
};
books.push(newBook);
res.status(201).json(newBook);
});
app.put('/books/:id', (req, res) => {
const bookId = parseInt(req.params.id);
const { title, author, year } = req.body;
const book = books.find(b => b.id === bookId);
if (!book) {
return res.status(404).json({ error: 'Book not found' });
}
if (title) book.title = title;
if (author) book.author = author;
if (year) book.year = year;
res.json(book);
});
app.delete('/books/:id', (req, res) => {
const bookId = parseInt(req.params.id);
const index = books.findIndex(b => b.id === bookId);
if (index === -1) {
return res.status(404).json({ error: 'Book not found' });
}
const deletedBook = books.splice(index, 1);
res.json({ message: 'Book deleted', book: deletedBook[0] });
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});