Enhance and streamline custom module code within a Node.js Express application

I am seeking suggestions on how to optimize the code within my custom module.

Below is the code for my module which you can review and provide feedback on.

    var employee = {
    all: function (req, res) {
        jwt.verify(req.token, 'novaturesol', (err) => {
            if (err) {
                res.status(400).send("Forbidden or token has expired!");
            } else {
                // database query.
                con.query("select * from employees limit 50", function (err, employees) {
                    if (err) throw err;
                    // console.log("Result: " + employees);
                    res.status(200).json(employees);
                });
            }
        });
    },
    create: function (req, res) {
        jwt.verify(req.token, 'novaturesol', (err) => {
            if (err) {
                res.status(400).send("Forbidden or token has expired!");
            } else {
                // validation array sent in response.
                const errors = validationResult(req);
                if (!errors.isEmpty()) {
                    return res.status(422).json({
                        errors: errors.array()
                    });
                }
                // generate random employee number.
                let employee_no = Math.floor(Math.random() * Math.floor(9000));
                // simple insert query.
                let sql = "INSERT INTO employees(emp_no, first_name, last_name, gender, birth_date, hire_date) VALUES('" + employee_no + "','" + req.body.first_name + "','" + req.body.last_name + "','" + req.body.gender + "','" + req.body.birth_date + "','" + req.body.hire_date + "')";
                con.query(sql, function (err, result) {
                    if (err) throw err;
                    console.log('Record inserted Successfully!');
                });
                // send response with last inserted employee id.
                res.status(200).send({
                    message: "Successfully added employee!",
                    last_employee_no: employee_no
                });
            }
        });
    },
    delete: function (req, res) {
        jwt.verify(req.token, 'novaturesol', (err) => {
            if (err) {
                res.status(400).send("Forbidden or token has expired!");
            } else {
                if (!req.body.employee_no) {
                    res.status(400).send({
                        message: "employee_no is required."
                    });
                } else if (isNaN(req.body.employee_no)) {
                    res.status(400).send({
                        message: "employee_no must be an integer."
                    });
                } else {
                    let employee_no = req.body.employee_no;
                    // delete record.
                    con.query("DELETE FROM employees where emp_no = '" + employee_no + "'")
                    res.status(200).send({
                        message: "Successfully deleted employee",
                        deleted_employee_no: employee_no
                    });
                }
            }
        });
    },
    update: function (req, res) {
        jwt.verify(req.token, 'novaturesol', (err) => {
            if (err) {
                res.status(400).send("Forbidden or token has expired!");
            } else {
                if (!req.body.employee_no) {
                    res.status(400).send({
                        message: "employee_no is required."
                    });
                } else if (isNaN(req.body.employee_no)) {
                    res.status(400).send({
                        message: "employee_no must be a number."
                    })
                } else if (!req.body.first_name) {
                    res.status(400).send({
                        message: "first_name is required."
                    });
                } else if (!req.body.last_name) {
                    res.status(400).send({
                        message: "last_name is required."
                    });
                } else if (!req.body.hire_date) {
                    res.status(400).send({
                        message: "hire_date is required."
                    });
                } else if (!req.body.birth_date) {
                    res.status(400).send({
                        message: "birth_date is required."
                    });
                } else if (!req.body.gender) {
                    res.status(400).send({
                        message: "gender is required."
                    });
                } else {
                    let employee_no = req.body.employee_no;
                    let first_name = req.body.first_name;
                    let last_name = req.body.last_name;
                    let gender = req.body.gender;
                    let hire_date = req.body.hire_date;
                    let birth_date = req.body.birth_date;
                    let sql = "UPDATE employees set first_name = '" + first_name + "' , last_name = '" + last_name + "', gender = '" + gender + "',  hire_date = '" + hire_date + "',  birth_date = '" + birth_date + "'  WHERE emp_no = '" + employee_no + "'";
                    console.log('the query ' + sql);
                    con.query(sql, function (err) {
                        if (err) throw err;
                    })
                    res.status(200).send({
                        message: "Successfuly updated employee record.",
                        updated_employee_no: employee_no
                    });
                }
            }
        });
    }
};
module.exports = employee;

Should I include jwt.verify for verification in each function?

Is there an alternative method to achieve this?

Regarding Database Queries: Is the way we write queries in node express like I have done correct? Or is there a more appropriate approach?

Answer №1

The current code structure is not ideal for maintainability. It is recommended to create repositories specifically for database queries in order to retrieve the necessary data for each section of your application. Additionally, when it comes to authentication, consider implementing middleware in Express to manage user authentication before accessing the employee controller. Avoid duplicating authentication logic repeatedly.

Here is an example repository you can refer to: areaRepository

As for the controller: userController

For authentication and other middleware functions, check out: middlewares

To improve clarity and organization, try to keep components separate and straightforward within each section of your codebase. Hopefully, these suggestions will help streamline your development process.

Answer №2

To prevent code repetitions, consider implementing a verify middleware that runs before each request.

Here is an example setup:

Note: This code has not been tested*


// Define verification middleware
function verifyJwt(req,res,next) {
   jwt.verify(req.token, 'novaturesol', (err) => {
     err ? res.locals.verified = false : res.locals.verified = true;
     next();
   })
}

// Implement middleware before routes
app.use(verifyJwt)

// Include verification in your module functions
var employee = {
  all: function (req, res) {
    if (res.locals.varified) {
      // Perform database query
      con.query("select * from employees limit 50", function (err, employees) {
        if (err) throw err;
        // console.log("Result: " + employees);
        res.status(200).json(employees);
      });
    }
  },...
}

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

Transforming JSON data into an interactive table with HTML

After spending four days searching for a solution, I am still unable to figure out my problem. My goal is to convert a JSON string data retrieved from a URL into a dynamic table using JQuery and JavaScript. To achieve this, I need to load the JSON string ...

What is the reason behind the "Error [ERR_HTTP_HEADERS_SENT]" being triggered by using "return next()"?

I built a custom Dialogflow chatbot designed to handle currency conversions. In my fulfillment code, I am utilizing an API to execute the conversion based on user input. However, I encountered an "Error [ERR_HTTP_HEADERS_SENT]" message when using "return n ...

Deactivate or modify the bodyparser function

Is it possible to turn off or replace the bodyparser functionality after adding it as middleware to an express app? In one file (which cannot be edited and is set up by the framework), the bodyParser.json() method is used: app.use(bodyParser.json()); expo ...

Sinon.js: How to create a mock for an object initialized with the new keyword

Here is the code that I am working with: var async = require('async'), util = require('util'); var Parse = require('parse/node'); function signup(userInfo, callback) { var username = userInfo.username, email ...

Extract latitude and longitude data using Mapbox's autocomplete feature

Currently, I have integrated Mapbox with autocomplete in a Vue component: <template> <div> <div id='geocoder'></div> </div> </template> <script> import mapboxgl from 'mapbox-gl& ...

Retrieve the weekday dates for a specific year, month, and relative week number using Javascript or Typescript

I am in need of a custom function called getDaysOfWeekDates that can take a year, a month (ranging from 0 to 11), and the week number of each month (usually 4-5 weeks per month) as parameters, and return a list of dates containing each day of that particul ...

Accessing variables within the controller's scope

Here is the JSON data I'm working with: { "id": "026001", "description": "Drop Forged Double Coupler", "CASHCUST01": { "hireRate": "0.01500", "saleRate": "2.50000" }, "SMITH00010": { "hireRate": "0.02500", "saleRate": "1.50000" }, " ...

Utilizing ng-switch for handling null values or empty strings

Can anyone assist me with this issue? I have a variable called $rootScope.user = {name:"abc",password:"asd"}. When a service response occurs, I am dynamically creating a rootscope variable by assigning it. How can I use ng-switch to check if the variable h ...

Attempting to generate printed documents with multiple components spread across individual pages using react-to-print

I am working with the react-to-print library and I have a requirement to print a list of components, with each component on its own separate page. However, when I click on the print button, I encounter an error stating that the argument does not appear to ...

Top method for invoking own API in Node.js

Is it a good practice to call your own API for building a website? What is the most effective way to call your own API on the same server within a Node.js application? One option is to simply call the API directly. Another option is to use socket.io with ...

Leverage the power of react-i18next in class-based components by utilizing decorators and Higher Order

Currently, I am working on implementing i18n into my React project that also utilizes Redux, with the assistance of react-i18next. In this particular project, we are using class components alongside decorators. Originally, I intended to experiment with r ...

Issue with Firefox causing problems with smooth scrolling Javascript on internal links

I recently created a one-page website using Bootstrap. The navigation menu items are internal links that point to different sections within the page, and I added some smooth scroll JavaScript for a more polished scrolling effect. While the website functio ...

Cryptocurrency price tracker with sleek Bitcoin symbol and FontAwesome icons

My assignment involved creating a function that retrieves Bitcoin trades from a JSON URL, allows users to change the interval with buttons, uses fontawesome arrows to indicate rate changes (up/down/no change), and displays the data on a website. Everythin ...

Dealing with the 503 Error in the Express framework of Node.js, especially when caught within a Try

I have encountered a unique scenario in which I am trying to troubleshoot the potential causes of a 503 Error. Below is a snippet of code where a catch statement is triggered if no results are found: app.post('/api/fetch/user', function(req, res ...

How can you create a unique record by appending a number in Javascript?

Currently, when a file already exists, I add a timestamp prefix to the filename to ensure it is unique. However, instead of using timestamps, I would like to use an ordinal suffix or simply append a number to the filename. I am considering adding an incr ...

Separate servers powering an HTTP server and web sockets

Setting up a http server (using express) and a socket server (socket.io) in Node.js is quite straightforward: var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); Is it ...

Enhancing Angular Directives with Dynamic Templates upon Data Loading

I am facing an issue with a directive that is receiving data from an api call. While the directive itself functions properly, the problem seems to be occurring because the directive loads before the api call is complete. As a result, instead of the expecte ...

Perform a function within another function in Vue

I am dealing with two nested functions in Vue. The parent function needs to retrieve the value of an attribute, while the child function is responsible for using this attribute value to make an API call. How can I ensure that both parts are executed simult ...

Shader designed to maintain the original lighting of the landscape

Currently, I have a shader set up to mix various textures for my terrain such as grass, sand, and rocks. While the blending is working well, the issue arises with compatibility with Three.js lighting engine. All vertices appear overly bright due to this ...

What is the best way to extract a certain property from a JSON string using JavaScript?

Can you guide me on how to extract the value of agent_code from this string using JavaScript? Additionally, could you please provide an explanation of the underlying logic? Abridged JSON Data: [{"name":"NYC","zone_id":"1","totalagents":"40","agents":[{ ...