Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
176 lines (149 loc) · 5.09 KB
/
Copy pathserver.js
File metadata and controls
176 lines (149 loc) · 5.09 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(cors());
app.use(bodyParser.json());
app.use(express.static('public'));
// Database file path
const DB_FILE = path.join(__dirname, 'data', 'books.json');
// Helper function to read books from JSON file
function readBooks() {
try {
const data = fs.readFileSync(DB_FILE, 'utf8');
return JSON.parse(data);
} catch (error) {
console.error('Error reading books:', error);
return [];
}
}
// Helper function to write books to JSON file
function writeBooks(books) {
try {
fs.writeFileSync(DB_FILE, JSON.stringify(books, null, 2));
return true;
} catch (error) {
console.error('Error writing books:', error);
return false;
}
}
// Helper function to generate unique ID
function generateId() {
const books = readBooks();
const maxId = books.reduce((max, book) => Math.max(max, parseInt(book.id)), 0);
return (maxId + 1).toString();
}
// API Routes
// GET /api/books - Get all books
app.get('/api/books', (req, res) => {
try {
const books = readBooks();
res.json(books);
} catch (error) {
res.status(500).json({ error: 'Failed to fetch books' });
}
});
// GET /api/books/:id - Get a specific book by ID
app.get('/api/books/:id', (req, res) => {
try {
const books = readBooks();
const book = books.find(b => b.id === req.params.id);
if (!book) {
return res.status(404).json({ error: 'Book not found' });
}
res.json(book);
} catch (error) {
res.status(500).json({ error: 'Failed to fetch book' });
}
});
// POST /api/books - Create a new book
app.post('/api/books', (req, res) => {
try {
const { title, author, genre, publishedYear, description, isbn, pages, rating, coverImage } = req.body;
// Validation
if (!title || !author) {
return res.status(400).json({ error: 'Title and author are required' });
}
const books = readBooks();
const newBook = {
id: generateId(),
title,
author,
genre: genre || 'Unknown',
publishedYear: publishedYear || new Date().getFullYear(),
description: description || '',
isbn: isbn || '',
pages: pages || 0,
rating: rating || 0,
coverImage: coverImage || 'https://images.unsplash.com/photo-1544947950-fa07a98d237f?w=300&h=400&fit=crop'
};
books.push(newBook);
if (writeBooks(books)) {
res.status(201).json(newBook);
} else {
res.status(500).json({ error: 'Failed to save book' });
}
} catch (error) {
res.status(500).json({ error: 'Failed to create book' });
}
});
// PUT /api/books/:id - Update a book
app.put('/api/books/:id', (req, res) => {
try {
const books = readBooks();
const bookIndex = books.findIndex(b => b.id === req.params.id);
if (bookIndex === -1) {
return res.status(404).json({ error: 'Book not found' });
}
const updatedBook = { ...books[bookIndex], ...req.body };
books[bookIndex] = updatedBook;
if (writeBooks(books)) {
res.json(updatedBook);
} else {
res.status(500).json({ error: 'Failed to update book' });
}
} catch (error) {
res.status(500).json({ error: 'Failed to update book' });
}
});
// DELETE /api/books/:id - Delete a book
app.delete('/api/books/:id', (req, res) => {
try {
const books = readBooks();
const filteredBooks = books.filter(b => b.id !== req.params.id);
if (filteredBooks.length === books.length) {
return res.status(404).json({ error: 'Book not found' });
}
if (writeBooks(filteredBooks)) {
res.json({ message: 'Book deleted successfully' });
} else {
res.status(500).json({ error: 'Failed to delete book' });
}
} catch (error) {
res.status(500).json({ error: 'Failed to delete book' });
}
});
// Serve the main HTML pages
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.get('/create', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'create.html'));
});
app.get('/book/:id', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'book-details.html'));
});
// Start server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
console.log(`API endpoints:`);
console.log(` GET /api/books - Get all books`);
console.log(` GET /api/books/:id - Get book by ID`);
console.log(` POST /api/books - Create new book`);
console.log(` PUT /api/books/:id - Update book`);
console.log(` DELETE /api/books/:id - Delete book`);
});