hello dev,
How are you?
This post is about a tip that leaves your code clean and with fewer lines of code. So the idea is to group similar routes in your project's routes file using express's route method.
When we create a CRUD in Nodejs we have a route for each operation and it happens that we often have similar routes that differ only in the request methods (get, post, put and delete).
Imagine that, you have your routes as follows:
router.get('/products', getProducts);
router.post('/products', createProducts);
router.put('/products/:id', updateProducts);
router.delete('/products/:id', deleteProducts);
Can you see that getProducts and createProducts are similar and only differ in the request method? Well, the same thing happens with updateProducts and deleteProducts.
So you can group similar routes as follows:
import { Router } from "express";
import { deleteProducts, getProducts, setProducts, updateProducts } from "../controllers/productsController";
const router = Router();
router.route('/').get(getProducts).post(setProducts);
router.route('/:id').put(updateProducts).delete(deleteProducts)
export { router }
Top comments (0)