node-backend-generator
Version:
🚀 CLI tool to generate professional Node.js backend templates with best practices, multiple databases, authentication, and production-ready features
117 lines (100 loc) • 2.75 kB
JavaScript
import express from 'express';
import mongoose from 'mongoose';
import cors from 'cors';
import helmet from 'helmet';
import compression from 'compression';
import { RateLimiterMemory } from 'rate-limiter-flexible';
import winston from 'winston';
import 'dotenv/config';
import notificationRoutes from './routes/notificationRoutes.js';
const app = express();
const PORT = process.env.PORT || 3003;
// Logger configuration
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [
new winston.transports.File({ filename: 'logs/error.log', level: 'error' }),
new winston.transports.File({ filename: 'logs/combined.log' })
]
});
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.simple()
}));
}
// Rate limiting
const rateLimiter = new RateLimiterMemory({
keyGenerator: (req) => req.ip,
points: 100,
duration: 60
});
// Middleware
app.use(helmet());
app.use(compression());
app.use(cors());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));
// Rate limiting middleware
app.use(async (req, res, next) => {
try {
await rateLimiter.consume(req.ip);
next();
} catch (rejRes) {
res.status(429).json({
success: false,
error: 'Too many requests'
});
}
});
// Health check
app.get('/health', (req, res) => {
res.json({
success: true,
message: 'notification service is healthy',
timestamp: new Date().toISOString(),
service: 'notification'
});
});
// Routes
app.use('/api/notification', notificationRoutes);
// Database connection
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/notification_service');
logger.info('MongoDB connected successfully');
} catch (error) {
logger.error('MongoDB connection error:', error);
process.exit(1);
}
};
// Error handling middleware
app.use((err, req, res, next) => {
logger.error('Unhandled error:', err);
res.status(500).json({
success: false,
error: process.env.NODE_ENV === 'production' ? 'Internal server error' : err.message
});
});
// 404 handler
app.use('*', (req, res) => {
res.status(404).json({
success: false,
error: 'Route not found'
});
});
const startServer = async () => {
await connectDB();
app.listen(PORT, () => {
logger.info(`notification service running on port ${PORT}`);
console.log(`notification service running on port ${PORT}`);
});
};
startServer().catch(error => {
logger.error('Failed to start server:', error);
process.exit(1);
});
export default app;