Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 17, 2022 04:24 am GMT

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.

Please follow me on instagram


Original Link: https://dev.to/frantchessico/how-to-create-crud-routes-in-nodejs-in-two-lines-only-l9e

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To