-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
96 lines (82 loc) · 2.48 KB
/
server.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
const express = require('express');
const http = require('http');
const cors = require('cors');
const helmet = require('helmet');
const sequelize = require('./config/db');
const authRoutes = require('./routes/authRoutes');
const paymentRoutes = require('./routes/paymentRoutes');
const { logger } = require('./utils/logger');
const healthCheck = require('./routes/healthCheck');
const errorHandler = require('./middleware/errorHandler');
const rateLimit = require('express-rate-limit');
const swaggerUi = require('swagger-ui-express');
const swaggerDocs = require('./swagger');
const app = express();
const port = 3000;
// Set up rate limiting
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 50, // Allow each IP 50 requests per 15 minutes
message: 'Too many requests from this IP, please try again later.',
headers: true,
});
// Apply rate limiting globally
app.use(limiter);
// Set security headers with Helmet
app.use(helmet());
// Customize Helmet (optional tweaks)
app.use(
helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'", 'https://fonts.googleapis.com'],
fontSrc: ["'self'", 'https://fonts.gstatic.com'],
},
},
crossOriginEmbedderPolicy: true,
crossOriginResourcePolicy: { policy: 'same-origin' },
})
);
// Enable CORS
app.use(cors());
// Body parsers
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Middleware for logging requests
app.use((req, res, next) => {
logger.info(`Incoming request: ${req.method} ${req.url}`);
next();
});
// Routes
app.use('/api', healthCheck);
app.use('/api/auth', authRoutes);
app.use('/api/payment', paymentRoutes);
// Swagger API Docs route
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));
// Root route
app.get('/', (req, res) => {
res.send('Payment Platform API is running!');
});
// Global error handler
app.use(errorHandler);
const server = http.createServer(app);
// Graceful Shutdown
process.on('SIGINT', () => {
console.log('Shutting down gracefully...');
server.close(() => {
console.log('Server has been shut down.');
process.exit(0); // Exit the process
});
});
// Sync database and start the server
sequelize.sync()
.then(() => {
app.listen(port, () => {
logger.info(`Server is running on port ${port}`);
});
})
.catch((error) => {
console.error('Error syncing database:', error);
logger.error('Error syncing database:', error.message);
});