An Interest In:
Web News this Week
- March 22, 2024
- March 21, 2024
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
April 17, 2022 04:24 am GMT
Original Link: https://dev.to/frantchessico/how-to-create-crud-routes-in-nodejs-in-two-lines-only-l9e
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);
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 }
Feel free to fork this repository on github and ask for a star.
Original Link: https://dev.to/frantchessico/how-to-create-crud-routes-in-nodejs-in-two-lines-only-l9e
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To