Skip to content
Open

Hw3 #20

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
PORT=3005
API_URL='http://localhost'
MONGODB_URI=mongodb://localhost:27017/mydb
2,909 changes: 2,909 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

20 changes: 15 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
{
"name": "@skypro-web-developer/backend-02-template",
"name": "@skypro-web-developer/backend-03-template",
"version": "1.0.0",
"description": "Шаблон для выполнения второго домашнего задания",
"description": "Шаблон для выполнения третьего домашнего задания",
"private": true,
"type": "module",
"main": "src/index.js",
"scripts": {
"dev": "",
"start": ""
"dev": "nodemon --exec \"node -r dotenv/config\" src/app.js",
"start": "node src/app.js"
},
"author": ""
"author": "",
"devDependencies": {
"nodemon": "^3.1.7"
},
"dependencies": {
"dotenv": "^16.4.5",
"express": "^4.21.1",
"helmet": "^8.0.0",
"mongoose": "^6.0.0"
}
}
21 changes: 21 additions & 0 deletions public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>API Test Page</title>
</head>

<body>

<h1>API Test Page</h1>
<p> Welcome to the API Test Page </p>
<p>Use this page to test your API endpoints. </p>

<h6>Error: Failed to fetch</h6>

</body>

</html>
67 changes: 67 additions & 0 deletions src/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import dotenv from 'dotenv';
dotenv.config();
import express from 'express';
import mongoose from 'mongoose';
import path from 'path';
import { fileURLToPath } from 'url';
import cors from './middlewares/cors.js';
import loggerMiddleware from './middlewares/logger.js';
import routes from './routes/index.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const app = express();
const { PORT = 3005, MONGODB_URI } = process.env;

if (!MONGODB_URI) {
console.error('MONGODB_URI is not defined in the environment variables');
process.exit(1);
}

mongoose.set('strictQuery', false);
mongoose.connect(MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('Connected to MongoDB'))
.catch((err) => {
console.error('Error connecting to MongoDB:', err);
process.exit(1);
});

app.use(express.json());
app.use(cors);
app.use(loggerMiddleware);

// Обслуживание статических файлов из папки public
app.use(express.static(path.join(__dirname, '..', 'public')));

// API маршруты
app.use('/api', routes);

// Для всех остальных маршрутов отправляем index.html
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '..', 'public', 'index.html'));
});

app.use((err, req, res, next) => {
console.error(err);
if (err instanceof mongoose.Error.CastError) {
return res.status(400).json({ message: 'Invalid ID format', details: err.message });
}
if (err instanceof mongoose.Error.ValidationError) {
const errors = Object.values(err.errors).map(error => error.message);
return res.status(400).json({ message: 'Validation Error', errors });
}
if (err.name === 'MongoServerError' && err.code === 11000) {
return res.status(400).json({ message: 'Duplicate key error', details: err.message });
}
res.status(500).json({ message: 'Internal server error', details: err.message });
});

app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});

export default app;
60 changes: 60 additions & 0 deletions src/controllers/book.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import Book from '../models/book.js';
import mongoose from 'mongoose';

export const getBooks = async (req, res, next) => {
try {
const books = await Book.find();
res.json(books);
} catch (err) {
next(err);
}
};

export const getBook = async (req, res, next) => {
try {
const { id } = req.params;
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).json({ message: 'Invalid book ID' });
}
const book = await Book.findById(id);
if (!book) {
return res.status(404).json({ message: 'Book not found' });
}
res.json(book);
} catch (err) {
next(err);
}
};

export const createBook = async (req, res, next) => {
try {
const book = await Book.create(req.body);
res.status(201).json(book);
} catch (err) {
next(err);
}
};

export const updateBook = async (req, res, next) => {
try {
const book = await Book.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true });
if (!book) {
return res.status(404).json({ message: 'Book not found' });
}
res.json(book);
} catch (err) {
next(err);
}
};

export const deleteBook = async (req, res, next) => {
try {
const book = await Book.findByIdAndDelete(req.params.id);
if (!book) {
return res.status(404).json({ message: 'Book not found' });
}
res.json({ message: 'Book deleted successfully' });
} catch (err) {
next(err);
}
};
68 changes: 68 additions & 0 deletions src/controllers/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import mongoose from 'mongoose';
import User from '../models/user.js';

export const getUsers = async (req, res, next) => {
try {
const users = await User.find();
res.json(users);
} catch (err) {
next(err);
}
};

export const getUser = async (req, res, next) => {
try {
const { id } = req.params;
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).json({ message: 'Invalid user ID format' });
}
const user = await User.findById(id);
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
res.json(user);
} catch (err) {
next(err);
}
};

export const createUser = async (req, res, next) => {
try {
const user = await User.create(req.body);
res.status(201).json(user);
} catch (err) {
next(err);
}
};

export const updateUser = async (req, res, next) => {
try {
const { id } = req.params;
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).json({ message: 'Invalid user ID format' });
}
const user = await User.findByIdAndUpdate(id, req.body, { new: true, runValidators: true });
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
res.json(user);
} catch (err) {
next(err);
}
};

export const deleteUser = async (req, res, next) => {
try {
const { id } = req.params;
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).json({ message: 'Invalid user ID format' });
}
const user = await User.findByIdAndDelete(id);
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
res.json({ message: 'User deleted successfully' });
} catch (err) {
next(err);
}
};
Loading