Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Separating routes into different modules

I’ve been putting my all routes into one server.js file, after a while i realised there is about 1000 lines in one file and it is hard to manage it. The question is there a simple way to seperate those routes into different route files without having to rewrite everything? Here is a snipped of my code, will not put whole code, it would take too much space

const bodyParser = require('body-parser');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const cors = require('cors');
const multer = require('multer');
const path = require('path');
const { Sequelize, DataTypes } = require('sequelize');

const sequelize = new Sequelize('school_canteen', 'root', 'password', {
 host: 'localhost',
 dialect: 'mysql'
});

const db = require('./db');
// const childrenRoutes = require('./routes/children');
const { User } = require('./models');
const { Order } = require('./models');
const menuitems = require('./models/menuitems');
const productCategory = require('./models/productCategory');
const Deal = require('./models/deal')(sequelize, DataTypes);
const { Product, ProductCategory, Menu,MenuItem } = require('./models');

const app = express();
const PORT = process.env.PORT || 3001;

app.use(cors());
app.use(bodyParser.json());
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

const storage = multer.diskStorage({
 destination: function (req, file, cb) {
   cb(null, 'uploads/');
 },
 filename: function (req, file, cb) {
   cb(null, `${Date.now()}-${file.originalname}`);
 }
});
const upload = multer({ storage: storage });

sequelize.sync().then(() => {
 console.log('Database synchronized');
}).catch(error => {
 console.error('Error synchronizing the database:', error);
});

const Photo = sequelize.define('Photo', {
 PhotoID: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true },
 photoUrl: { type: Sequelize.STRING, allowNull: false },
 productId: { type: Sequelize.INTEGER, allowNull: false },
 altText: { type: Sequelize.STRING, allowNull: true }
}, {
 tableName: 'photos'
});


const Child = sequelize.define('Child', {
 Name: { type: Sequelize.STRING, allowNull: false },
 Surname: { type: Sequelize.STRING, allowNull: false },
 Grade: { type: Sequelize.STRING, allowNull: false },
 UserID: { type: Sequelize.INTEGER, allowNull: false }
}, {
 tableName: 'children'
});

const authenticateToken = (req, res, next) => {
 const authHeader = req.headers['authorization'];
 const token = authHeader && authHeader.split(' ')[1];
 
 console.log('Token received:', token);

 if (token == null) return res.sendStatus(401);

 jwt.verify(token, 'your_secret_key_here', (err, user) => {
   if (err) {
     console.error('Token verification failed:', err);
     return res.sendStatus(403);
   }
   req.user = user;
   console.log('User from token:', user);
   next();
 });
};

const isAdmin = async (req, res, next) => {
 try {
   const user = await db.User.findByPk(req.user.id);
   if (user && user.RoleID === 2) {
     next();
   } else {
     res.sendStatus(403);
   }
 } catch (err) {
   res.sendStatus(500);
 }
};

app.post('/api/admin/photos', authenticateToken, isAdmin, upload.single('photo'), async (req, res) => {
 const { productId, altText } = req.body;
 const photoUrl = req.file ? req.file.path : undefined;

 console.log('Request Body:', req.body);
 console.log('Uploaded File:', req.file);

 if (!productId || !photoUrl) {
   return res.status(400).json({ error: 'ProductID and PhotoURL are required' });
 }

 try {
   const newPhoto = await Photo.create({
     photoUrl,
     productId,
     altText
   });
   res.status(201).json(newPhoto);
 } catch (err) {
   console.error('Error creating photo:', err);
   res.status(500).send('Server Error');
 }
});

app.put('/api/admin/photos/:photoId', authenticateToken, isAdmin, upload.single('photo'), async (req, res) => {
 const { photoId } = req.params;
 const { productId, altText } = req.body;
 const photoUrl = req.file ? req.file.path : undefined;

 try {
   const photo = await Photo.findByPk(photoId);
   if (!photo) return res.status(404).json({ msg: 'Photo not found' });

   photo.productId = productId || photo.productId;
   photo.altText = altText || photo.altText;
   if (photoUrl) { 
     photo.photoUrl = photoUrl;
   }
   await photo.save();
   res.json(photo);
 } catch (err) {
   console.error(err.message);
   res.status(500).send('Server Error');
 }
});

app.delete('/api/admin/photos/:photoId', authenticateToken, async (req, res) => {
 const { photoId } = req.params;

 try {
   const photo = await Photo.findByPk(photoId);
   if (!photo) {
     return res.status(404).json({ error: 'Photo not found' });
   }

   await photo.destroy();
   res.status(200).json({ message: 'Photo deleted successfully' });
 } catch (error) {
   console.error('Error deleting photo:', error);
   res.status(500).json({ error: 'Failed to delete photo' });
 }
});


app.get('/api/photos', authenticateToken, async (req, res) => {
 try {
   const photos = await Photo.findAll();
   res.json(photos);
 } catch (error) {
   console.error('Error fetching photos:', error);
   res.status(500).json({ error: 'Failed to fetch photos' });
 }
});

app.get('/photos/:productId', authenticateToken, async (req, res) => {
 try {
   const photos = await Photo.findAll({ where: { productId: req.params.productId } });
   res.json(photos);
 } catch (err) {
   console.error('Error fetching photos:', err.message);
   res.status(500).send('Server Error');
 }
});
app.listen(PORT, () => {
 console.log(`Server running on port ${PORT}`);
});

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Create a Routes folder and also create route files in there

// Routes
const adminRoute = require('./Routes/Admin');
const photoRoute = require('./Routes/Photos');

And add it into to your main.js like code snippet.
After it please add this too for let the express manage your requests on it.

// Routers
app.use('/admin', adminRoute);
app.use('/photo', photoRoute);

One of your route file should be something like that

//Library
const express = require('express');

const router = express.Router();

//Routes
router.post('/photo' , yourEndpointFunction);
router.post('/anything' , yourEndpointFunctionComesHere);

module.exports = router;

Put your endpoint function to here also, you can pull that function from another file too.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading