DEV Community

Cover image for How to create CRUD routes in Nodejs in two lines only.
Francisco  Inoque
Francisco Inoque

Posted on

How to create CRUD routes in Nodejs in two lines only.

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);
Enter fullscreen mode Exit fullscreen mode

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 }
Enter fullscreen mode Exit fullscreen mode

Feel free to fork this repository on github and ask for a star.

Please follow me on instagram

Discussion (0)