Effective Ways to Segregate CRUD Endpoints in Node.js with Express

When you wish to consolidate all CRUD operations for your model into one file, it is typically done using the following structure as shown in our first method:

routes.js

const express = require("express");
const users = require("../routes/users");

module.exports = function (app) {
    app.use(express.json());
    app.use("/api/user", users);
};

users.js

router.patch("/", auth, async (req, res) => {
    // create and update operations ...
})

router.delete("/:id", auth, async (req, res) => {
    // delete operations ...
})
module.exports = router



However, if you prefer having separate files for each CRUD operation, you can achieve this using a different approach known as the second method. Here's how the directory structure would look like:
users
|__patchUser.js
|__deleteUser.js
|__index.js

The index file should resemble the following:
index.js

const express = require("express");
const router = express.Router();
module.exports = router;

Furthermore, the other individual files will be structured as follows:
patchUser.js

const router = require("./index");

router.patch("/", auth, async (req, res) => {

})

Unfortunately, this setup does not work as expected.

How can we correct the second method to have distinct CRUD routing files?

Answer №1

It is recommended to structure your code in the following way. Within the index.js file, only include calls to routes such as userRoutes and productRoutes.

index.js

 const express = require('express');
 const userRoutes = require('./routes/user);
    
 const app = express();
 app.use('/api/user',userRoutes);

Inside the routes Folder
user.js

const router = require('express')().Router;
const patchUser = require('./controllers/user/PatchUser');
const deleteUser = require('./controllers/user/DeleteUser');
const auth = require('./middleware/auth);
//Ensure middlewares are kept in separate files

router.patch('/',auth,patchUser);
router.delete('/:id',auth,deleteUser);

module.exports = router;

Inside the controllers folder
folder named user

PatchUser.js

const patchUser = async(req,res,next)=>{
//todo
}

module.exports = patchUser;

DeleteUser.js

const deleteUser = async(req,res,next)=>{
//todo
}
module.exports = deleteUser;

To make things simpler, follow these steps:

  1. Create a PatchUser.js file within controllers/user/.
  2. Create a userRoutes.js file in the routes directory.
  3. Update the index.js file.
  4. Create a DeleteUser.js file within controllers/user/.
  5. Update the userRoutes.js file
  6. Update the index.js file

Initially, this may seem challenging, but with practice it will become easier and set the foundation for clean architecture.

I hope this aligns with what you were seeking.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determine the height of an image using JavaScript

How can I retrieve the height of an image in a JavaScript function? When I use the code: var image_height = $(image).height(); The value of image_height is 0, even though my image definitely has non-zero height. Is there a different method to accurately ...

Using jQuery Ajax and PHP for Secure User Authentication

Hello everyone, I could really use some assistance right now. The issue I'm facing is that the error div is not showing the content I expect in the success function of my AJAX request. I've tried alerting the response, which returns true if the ...

I am unable to employ the useMutation or useQuery features in Apollo Client 3.0

import { useMutation } from '@apollo/client';; function LockedBlog() { const [lockedBlog] = useMutation(LOCKED_BLOG); }; class EditBlog extends Component { state = { ...initialState }; index.js import React from "react"; im ...

Guide on utilizing the eval() function to assign a value to a field passed as a parameter

I am interested in achieving the following: function modifyField(fieldName){ eval(fieldName) = 1234; } In simpler terms, I want to pass a specific field name as a parameter and then assign a value to that field. Can someone guide me on how to accomp ...

Unlocking bundles of worth through javascript coding

Is there a way to retrieve a set of values using javascript? Upon page load, I am looking to display an alert showing the value '0-1' for any checked checkboxes. View example here var checkBoxes = document.getElementsByName('mailId[]&apos ...

JavaScript: inscribe in a specific cell

I have a table cell within a div element and I am trying to display the date for the last Thursday in it: <body> <div> <table id="TableName" width="auto"> <thead> <tr> ... ...

Showing data retrieved from nested JSON arrays in React Native

Recently, I delved into the world of React Native and encountered a challenge in displaying nested elements from fetched JSON data. Despite utilizing react hooks in the fetch API, I couldn't quite crack the code. export default function MedProfilScre ...

ExpressJS Template Caching System

Encountering issues with template caching in my MEAN app. The navigation bar uses conditional logic to show/hide buttons based on user status. Upon page load, values are null or false until login (views, isLoggedIn). The problem arises post-login - despit ...

Updating values in an Object by assigning them with results from an array

I've been grappling with a data structure issue in nodejs and I could really use some assistance. Here's the scenario: I have an object: let obj = { commenter: '', comment: '', numberOflikes: 0, } Along with a containe ...

Unable to persist data in MongoDB (Image of PopUp)

I encountered a problem where out of the 4 img options in the code below, only one image is not being saved to MongoDB (img2 from the popup). The other three images are being saved successfully. <div className="mt-10 grid grid-cols-1 gap-x-6 gap- ...

Guide on updating a key's value in an object

Hello, I am a newcomer to working with react redux. Currently, I have an array of objects structured like this: let result = [ {Id :'a',temp:5,data:'abc (c:1'},{Id :'a',temp:5,data:'pqr (c:1'}{Id :'a',temp ...

What is the best approach to restructuring this code with an excessive number of $routeProvider routes in a single file?

After researching how to effectively wire up Angular with Express + Node, I stumbled upon a helpful article. One key takeaway was the ability to serve Angular templates from the same directory as views using the line of code: app.set('views', _ ...

Utilizing AngularJS "controller as" syntax within templates

Recently diving into the AngularJS world, I embarked on setting up a simple laravel/angular JWT authentication by following this specific tutorial. My goal is to utilize the "Controller As" syntax instead of relying on $scope as instructed in the tutorial ...

Steps to retrieve a base64 image using Cordova's FileTransfer feature

Recently, I encountered an issue with downloading base-64 images using the Cordova file transfer protocol. When I tried to provide a remote server path like "", the download worked perfectly. However, when I attempted to use a base-64 image path for the fi ...

Activate the scroll bar once the timer has finished counting down

Can someone assist me with enabling the scrollbar on my website after a certain duration of an intro? I'm struggling with figuring out how to do this. Below is the code snippet I have so far: let intro = do ...

Please provide me with the steps to relocate the src/pages/api folder to src/ in a Next.js project

When working with Next.js, I am interested in relocating the src/pages/api directory to be located under src/, much like how it is done in blitz.js. In this case, the directory structure would look something like this: src |- pages |- api Unfortunately, I ...

Utilize jQuery to target and select all elements whose class names begin with

If I have elements with classnames like this: .ses_0 .ses_1 .ses_2 .ses_3 How can I select all the elements and append them with a certain snippet? For example: var sessions = $('*[class*=ses_]'); for (var i = 0; i < sessions.le ...

Warning on React component listing due to key issue originating from the parent component

Alert: It is essential that each child in a list has a distinct "key" prop. Please review the render method of ForwardRef(ListItem). A child from RecipientsList was passed. I have located this issue using the react-components debugger tool on Chrome. I ad ...

Protractor struggling to drag an element, but cannot successfully drop it

I've been utilizing Protractor to test my AngularJS application, specifically focusing on dragging an element and dropping it onto an SVG. So far, I've managed to successfully click and drag the element over the SVG. browser.actions() .mouse ...

Transfer the text from one cell and insert it into the "neighbor" cell of a different column when the content is editable

present situation: Clicking on a row fills the entire row of another column, instead of just filling a single row. <p class="p-of-that" v-html="thatText" contenteditable @click="writeThat(myArr, $event)" ></p& ...