-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
85 lines (70 loc) · 2.32 KB
/
Copy pathapp.js
File metadata and controls
85 lines (70 loc) · 2.32 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
// book-management-api/index.js
const express = require('express');
const { v4: uuidv4 } = require('uuid');
const fs = require('fs');
const multer = require('multer');
const morgan = require('morgan');
const csv = require('csv-parser');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 3000;
app.use(express.json());
app.use(morgan('dev'));
const upload = multer({ dest: 'uploads/' });
let books = [];
// CRUD ENDPOINTS
app.get('/books', (req, res) => {
res.json(books);
});
app.get('/books/:id', (req, res) => {
const book = books.find(b => b.id === req.params.id);
book ? res.json(book) : res.status(404).json({ message: 'Book not found' });
});
app.post('/books', (req, res) => {
const { title, author, publishedYear } = req.body;
if (!title || !author || typeof publishedYear !== 'number') {
return res.status(400).json({ message: 'Invalid book data' });
}
const newBook = { id: uuidv4(), title, author, publishedYear };
books.push(newBook);
res.status(201).json(newBook);
});
app.put('/books/:id', (req, res) => {
const { title, author, publishedYear } = req.body;
const index = books.findIndex(b => b.id === req.params.id);
if (index === -1) return res.status(404).json({ message: 'Book not found' });
books[index] = { ...books[index], title, author, publishedYear };
res.json(books[index]);
});
app.delete('/books/:id', (req, res) => {
books = books.filter(b => b.id !== req.params.id);
res.status(204).send();
});
// CSV IMPORT
app.post('/books/import', upload.single('file'), (req, res) => {
const errors = [];
let addedCount = 0;
fs.createReadStream(req.file.path)
.pipe(csv())
.on('data', (data) => {
const { title, author, publishedYear } = data;
if (!title || !author || isNaN(Number(publishedYear))) {
errors.push({ ...data, error: 'Invalid data' });
} else {
books.push({ id: uuidv4(), title, author, publishedYear: Number(publishedYear) });
addedCount++;
}
})
.on('end', () => {
fs.unlinkSync(req.file.path);
res.json({ added: addedCount, errors });
});
});
// ERROR HANDLING MIDDLEWARE
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
app.listen(port, () => {
console.log(Book API listening at http://localhost:${port});
});