-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
91 lines (75 loc) · 2.39 KB
/
Copy pathapp.js
File metadata and controls
91 lines (75 loc) · 2.39 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
import 'dotenv/config';
import express, { json, urlencoded } from 'express';
import cors from 'cors';
import morgan from 'morgan';
import rateLimit from 'express-rate-limit';
import swaggerUi from 'swagger-ui-express';
import swaggerSpec from './swagger/swagger.js';
import connectDB from './config/db.js';
import errorHandler from './middlewares/errorHandler.js';
import authRoutes from './routes/authRoutes.js';
import transactionRoutes from './routes/transactionRoutes.js';
import dashboardRoutes from './routes/dashboardRoutes.js';
import userRoutes from './routes/userRoutes.js';
const { serve, setup } = swaggerUi;
const app = express();
// Connect to MongoDB
if (process.env.NODE_ENV !== 'test') {
connectDB();
}
// Middleware
app.use(cors());
app.use(json());
app.use(urlencoded({ extended: true }));
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
}
// Rate limiting - 100 requests per 15 minutes per IP
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
standardHeaders: true,
legacyHeaders: false,
message: { success: false, message: 'Too many requests. Please try again later.' },
});
app.use('/api', limiter);
// API docs
app.use('/api/docs', serve, setup(swaggerSpec, {
customSiteTitle: 'Finance Dashboard API',
customCss: '.swagger-ui .topbar { background-color: #1a1a2e; }',
}));
// Routes
app.use('/api/auth', authRoutes);
app.use('/api/transactions', transactionRoutes);
app.use('/api/dashboard', dashboardRoutes);
app.use('/api/users', userRoutes);
// Root route for browser and API clients
app.get('/', (req, res) => {
if (req.accepts('html')) {
return res.redirect('/api/docs');
}
return res.status(200).json({
success: true,
message: 'Finance Dashboard API is running.',
docs: '/api/docs',
health: '/health',
});
});
// Health check
app.get('/health', (req, res) => {
res.json({ success: true, message: 'Finance Dashboard API is running', timestamp: new Date() });
});
// 404 handler
app.use((req, res) => {
res.status(404).json({ success: false, message: `Route ${req.originalUrl} not found.` });
});
// Global error handler
app.use(errorHandler);
const PORT = process.env.PORT || 3000;
if (process.env.NODE_ENV !== 'test') {
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log(`API docs available at http://localhost:${PORT}/api/docs`);
});
}
export default app;