ecomm/src/index.ts

55 lines
1.2 KiB
TypeScript

import express from 'express';
import mongoose from 'mongoose';
import cookieParser from 'cookie-parser';
import userRouter from './routes/userRouter';
import productRouter from './routes/productRouter';
import cartRouter from './routes/cartRouter';
import { errorHandler } from './middlewares/errorHandler';
const env = require('dotenv').config().parsed;
const app = express();
const PORT = env.PORT || 3000;
app.use(express.json());
app.use(cookieParser())
// Connect to MongoDB using Mongoose
mongoose.connect(env.DATABASE_URL);
const db = mongoose.connection;
// Check for DB connection
db.on('error', () => {
console.error.bind(console, 'MongoDB connection error:')
process.exit(1);
});
db.once('open', () => {
console.log('Connected to MongoDB');
});
// Routes
app.use('/users', userRouter);
app.use('/products', productRouter);
app.use('/cart', cartRouter);
app.all('*', (req, res, next) => {
// res.status(404).json({ error: 'Route not found' });
const error = new Error('Route not found');
// error.statusCode = 404;
// error.status = 'fail';
next(error)
});
app.use(errorHandler);
// Start server
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});