-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
118 lines (100 loc) · 4.83 KB
/
app.js
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
const express = require('express');
const app = express();
const config = require('./config/config');
const db = require('./models');
const authRoutes = require('./routes/authRoutes');
const userRoutes = require('./routes/userRoutes');
const notificationRoutes = require('./routes/notificationRoutes');
const errorHandler = require('./middleware/errorHandler');
const { scheduleNotifications } = require('./services/notificationService');
const bcrypt = require('bcryptjs');
const logger = require('./utils/logger');
const { swaggerUi, swaggerSpec } = require('./swagger');
const morgan = require('morgan');
const helmet = require('helmet'); // Добавляем helmet
const cors = require('cors'); // Добавляем CORS
// Middleware
app.use(express.json());
// Безопасность заголовков с helmet
app.use(helmet());
// Настройка CORS
const corsOptions = {
origin: process.env.CORS_ORIGIN || '*', // Разрешаем все домены (можно настроить на конкретные)
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
};
app.use(cors(corsOptions)); // Используем CORS middleware
app.use((err, req, res, next) => {
if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
// Если возникла ошибка парсинга JSON
console.error('Ошибка парсинга JSON:', err.message);
return res.status(400).json({
error: 'Некорректный JSON в запросе',
});
}
next();
});
// Логирование HTTP-запросов
app.use(morgan('combined'));
// Swagger документация
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec, { explorer: true }));
// Маршрут для выдачи JSON спецификации
app.get('/api-docs.json', (req, res) => {
res.setHeader('Content-Type', 'application/json');
res.send(swaggerSpec);
});
// Маршруты
app.use(authRoutes);
app.use(userRoutes);
app.use(notificationRoutes);
// Обработчик ошибок
app.use(errorHandler);
// Логирование текущего окружения и порта
console.log(`Текущее окружение: ${process.env.NODE_ENV}`);
console.log(`Используемый порт: ${process.env.PORT || 3000}`);
// Получение публичного URL из переменной окружения или использование localhost как резервный вариант
const publicUrl = process.env.PUBLIC_URL || `http://localhost:${process.env.PORT || 10000}`;
// Синхронизация базы данных и запуск сервера
db.sequelize.sync().then(async () => {
try {
console.log('Подключение к базе данных успешно.');
// Создание администратора по умолчанию, если его нет
const existingAdmin = await db.User.findOne({ where: { role: 'admin' } });
if (!existingAdmin) {
console.log('Администратор не найден. Создаём администратора по умолчанию...');
const hashedPassword = await bcrypt.hash('adminpassword', 10);
await db.User.create({
firstName: 'Default',
lastName: 'Admin',
middleName: 'User',
birthDate: '1970-01-01',
phone: '+0000000000',
email: '[email protected]',
programmingLanguage: 'N/A',
password: hashedPassword,
role: 'admin',
hireDate: '2020-04-04',
});
console.log('Администратор по умолчанию создан: [email protected] / adminpassword');
} else {
console.log('Администратор уже существует.');
}
// Запуск планировщика уведомлений
console.log('Запуск планировщика уведомлений...');
scheduleNotifications();
console.log('Планировщик уведомлений успешно запущен.');
// Запуск сервера
const port = process.env.PORT || 10000;
app.listen(port, () => {
console.log(`Сервер запущен на порту ${port}`);
console.log(`OpenAPI доступна по адресу ${publicUrl}/api-docs`);
});
} catch (err) {
console.error('Ошибка при запуске приложения:', err);
logger.error('Не удалось запустить приложение:', err);
}
}).catch((err) => {
console.error('Ошибка синхронизации базы данных:', err);
logger.error('Ошибка синхронизации базы данных:', err);
});
module.exports = app;