Back to Express JS Course
Express JS Course
In the context of Express JS, routers are used to organize routes in a modular way. This helps to keep your application clean and maintainable, especially as it grows larger.
Lets refactor our code to include routers.
validationSchemas.mjs
export const createUserValidationSchema = { name: { isLength: { options: { min: 5, max: 32, }, errorMessage: "name must be at least 5 characters with a max of 32 characters", }, notEmpty: { errorMessage: "name cannot be empty", }, isString: { errorMessage: "name must be a string!", }, }, designation: { notEmpty: true, }, city: { notEmpty: true, }, };
userRouter.mjs
import express from 'express'; import { checkSchema, validationResult } from 'express-validator'; import { createUserValidationSchema } from '../utils/validationSchemas.mjs'; const router = express.Router(); const mockUsers = [ { id: 1, name: 'Praveen', designation: 'Technical Architect', city: 'Hyderabad' }, { id: 2, name: 'Prasad', designation: 'Technical Lead', city: 'Bangalore' }, { id: 3, name: 'Anusha', designation: 'Lead Developer', city: 'Chennai' }, { id: 4, name: 'Ravi', designation: 'Developer', city: 'Hyderabad' }, { id: 5, name: 'Kiran', designation: 'Technical Lead', city: 'Hyderabad' }, ]; // Middleware for authentication const authenticate = (req, res, next) => { const apiKey = req.headers['x-api-key']; if (apiKey && apiKey === '2a5699ae-6e99-4cac-ae55-bb769d9e6090') { next(); } else { res.status(401).send('Unauthorized'); } }; // Route to get all users router.get('/', authenticate, (req, res) => { let filteredUsers = mockUsers; const { name, designation, city } = req.query; if (name) { filteredUsers = filteredUsers.filter(user => user.name.toLowerCase().includes(name.toLowerCase())); } if (designation) { filteredUsers = filteredUsers.filter(user => user.designation.toLowerCase().includes(designation.toLowerCase())); } if (city) { filteredUsers = filteredUsers.filter(user => user.city.toLowerCase().includes(city.toLowerCase())); } res.send({ users: filteredUsers }); }); // Route to get a single user by ID router.get('/:id', (req, res) => { const parsedId = parseInt(req.params.id); if (isNaN(parsedId)) res.status(400).send({ msg: "Bad Request. Invalid ID" }); const findUser = mockUsers.find((user) => user.id === parsedId); if (!findUser) res.status(404).send({ msg: "ID Not Found" }); res.send(findUser); }); // Route to add a new user router.post('/', checkSchema(createUserValidationSchema), (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } const newUser = req.body; // Validate the incoming data if (!newUser.name || !newUser.designation || !newUser.city) { return res.status(400).send({ msg: 'Bad Request. Missing required fields' }); } // Assign a new ID to the new user newUser.id = mockUsers.length ? mockUsers[mockUsers.length - 1].id + 1 : 1; // Add the new user to the mockUsers array mockUsers.push(newUser); // Respond with the newly created user res.status(201).send({ user: newUser }); }); // Route to update an existing user router.put('/:id', (req, res) => { const parsedId = parseInt(req.params.id, 10); if (isNaN(parsedId)) { return res.status(400).send({ msg: 'Bad Request. Invalid ID' }); } const findUser = mockUsers.find((user) => user.id === parsedId); if (!findUser) { return res.status(404).send({ msg: 'ID Not Found' }); } const { name, designation, city } = req.body; if (!name || !designation || !city) { return res.status(400).send({ msg: 'Bad Request. Missing required fields' }); } // Update user data findUser.name = name; findUser.designation = designation; findUser.city = city; res.send({ user: findUser }); }); // PATCH endpoint to update user by ID router.patch('/:id', (req, res) => { const id = parseInt(req.params.id); const updatedUser = req.body; // Find the user by ID const userToUpdate = mockUsers.find(user => user.id === id); // If the user is found, update its properties if (userToUpdate) { userToUpdate.name = updatedUser.name; userToUpdate.designation = updatedUser.designation; userToUpdate.city = updatedUser.city; res.status(200).json({ message: 'User updated successfully', user: userToUpdate }); } else { res.status(404).json({ message: 'User not found' }); } }); // Route to delete a user router.delete('/:id', (req, res) => { const userId = parseInt(req.params.id); const userIndex = mockUsers.findIndex(user => user.id === userId); if (userIndex !== -1) { mockUsers.splice(userIndex, 1); res.status(204).send(); // No Content } else { res.status(404).send('User not found'); } }); export default router;
index.mjs
import express from 'express'; import usersRouter from './routes/usersRouter.mjs'; const app = express(); const PORT = process.env.PORT || 5000; // Middleware to parse JSON bodies app.use(express.json()); // Middleware to log requests app.use((req, res, next) => { console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`); next(); }); // Route for the home page app.get('/', (req, res) => res.send({ msg: "Welcome To Praveen Oruganti!" })); // Mounting the usersRouter for all routes starting with /api/v1_0/users app.use('/api/v1_0/users', usersRouter); // Start the server app.listen(PORT, () => console.log(`Running on Port ${PORT}`));
Lets invoke get all users endpoint
