Send a middleware out of a middleware function

I'm currently utilizing express-validator and I'm looking to implement varying checks based on a value in the request body.

Although I've created a function for this purpose, it seems that I'm not receiving any responses back from express:

validation/profile.js

module.exports = function (req,res,next) {
    if (req.body.type == 'teacher') {
        return check('name').exists().withMessage('Name is required'),
    } else {
        return check('student_id').exists().withMessage('Student id is required'),
    }
}

app.js

router.put('/', require('./validation/profile'), (req, res, next) => {
    const errors = validationResult(req).formatWith(errorFormatter)
    if (!errors.isEmpty()) {
        return res.status(422).json({ errors: errors.mapped() })
    } else {
        res.send(req.user)
    }  
})

However, when I write the function as a standard function instead of middleware with three params and call it, everything works. The downside is that I lose access to the request object. In this case, I have to hard-code the params.

validation/profile.js

module.exports = function (type) {
    if (type == 'teacher') {
        return check('name').exists().withMessage('Name is required'),
    } else {
        return check('student_id').exists().withMessage('Student id is required'),
    }
}

app.js

router.put('/', require('./validation/profile')('teacher'), (req, res, next) => {
    const errors = validationResult(req).formatWith(errorFormatter)
    if (!errors.isEmpty()) {
        return res.status(422).json({ errors: errors.mapped() })
    } else {
        res.send(req.user)
    }  
})

Any recommendations on how I can achieve different validation checks based on the request body's value?

Answer №1

When using the express-validator library, the check API is utilized to create middleware that can be attached directly to express or called manually as needed.

// Set up routers for attaching multiple checks

const teacherChecks = express.Router();
teacherChecks.use(check('name').exists().withMessage('Name is required'));

const studentChecks = express.Router();
studentChecks .use(check('student_id').exists().withMessage('Student id is required'));

module.exports = function (req,res,next) {
    if (req.body.type == 'teacher') {
        teacherChecks(req, res, next);
    } else {
        studentChecks(req, res, next);
    }
}

Another option is to use oneOf to achieve a similar outcome.

router.put('/', oneOf([
    check('name').exists().withMessage('Name is required'),
    check('student_id').exists().withMessage('Student id is required')
], 'Invalid request body'), (req, res, next) => {
    const errors = validationResult(req).formatWith(errorFormatter)
    if (
        !errors.isEmpty()
    ) {
        return res.status(422).json({errors: errors.mapped()})
    }
    else {
        res.send(req.user)
    }
});

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

Express.js does not display console.log messages while routing

Just starting to explore Express and its middleware functions. var express = require('express'); var app = express(); app.get('/', function(req, res) { res.send('id: ' + req.params.id + ' and name: ' + req.param ...

Is it possible to reach the maximum write capacity per second per database if I create a document using Promise.all in this manner?

I'm currently in the process of developing an app and I need to send a message to all my users' inboxes. The code I'm using in my cloud functions looks like this: const query = db.collection(`users`) .where("las ...

The creation of the Angular project was unsuccessful due to the outdated circular-json dependency

After attempting to create a new Angular project with the command: ng new hello-world I encountered an error message: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5d6dcc7d6c0d9d4c798dfc6dadbf5859b809b8 ...

Connecting text input to the server in order to run a command-line application based on the provided text input

As part of my learning journey, I am embarking on the creation of a simplified version of codepad.org, with C being the initial programming language I aim to support. To provide some context: If I were developing a basic note-taking web application (simil ...

Retrieve data from package.json configuration variables

I recently implemented https://www.npmjs.com/package/config to manage my configuration settings: ... config/ dev.json uat.json production.json package.json In the dev.json file, I have something similar to this: { "someVar": "something" ...

Protected HTTP Live Streaming 128-bit AES encryption key location

After encrypting a video using HLS AES-128 with the apple tool, I have generated an m3u8 file that looks like this: #EXTM3U #EXT-X-TARGETDURATION:10 #EXT-X-MEDIA-SEQUENCE:0 #EXT-X-PLAYLIST-TYPE:VOD #EXT-X-KEY:METHOD=AES-128,URI="https://xxxxx.com/api/ ...

The initial io.emit message seems to always be delayed or lost in transmission

io.on('connection',function(socket){ console.log('connected'); socket.on('disconnect',()=>{ console.log('a user disconnected'); }); socket.on('sendMessage',function(data){ const message = data.te ...

Combining multer, CSRF protection, and express-validator in a Node.js environment

Within my node.js application, I am utilizing an ejs form that consists of text input fields in need of validation by express-validator, an image file managed by multer, and a hidden input housing a CSRF token (a token present in all other forms within the ...

What is the best way to transform a JSON result from mongoose into an array?

I have a code snippet that displays the output and I am looking to transform this output into an array. TranModel .find({ quantityout: 1 }, { _id: 0} ) .sort({ tag: 1 }) .select( 'tag' ) . ...

Interrupt the sequence of promises - prevent the subsequent 'then' function from running

I'm currently working on developing a registration system using Node/Express and I've been experimenting with Promises. However, I've encountered an error message while incorporating them: Error: (node:64725) UnhandledPromiseRejectionWa ...

Refreshing the Angular page using ng-route in html5 mode fails to redirect to index.html

My goal is to implement html5 mode for my mean app. Below is the view router code in my angular script: app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) { $routeProvider // define r ...

Guide to implementing error handling middleware in Express 4.x

Despite setting process.env.NODE_ENV ='development', I attempted to use middleware errorhandler, but it failed to work. Here is the server code: var express = require('express'); var app = express(); var errorhandler = require('e ...

Send a response from socket.io to the client's browser

I am working on a project where I need to retrieve the ID of the current drawer from the server and pass it to the client. Here is the code I have so far: Client Side: socket.emit('returnDrawer'); socket.on('returnDrawer', fu ...

Tips for representing an anonymous JavaScript function in a UML class diagram

Looking to create a class diagram for a single class as an illustration. This particular class includes an anonymous callback function. How can I effectively represent this function in the class diagram? If I were to write the function as: +function(req, ...

The installation of becrypt with npm failed on the Debian Weezy system

I am facing difficulties installing bcrypt on Debian Wheezy. Whenever I try to install it using the command "npm install bcrypt", an error occurs. The error message is as follows: npm install bcrypt / > [email protected] install /home/abdulmanaf/ ...

Retrieve country data using AngularJS with Google API

Hi there! I'm currently working on extracting the country name from the Google API and storing it in a scope variable. However, I seem to be encountering issues with the function $scope.getLatLon as it is not returning the expected output. As a newcom ...

Beanstalk's NPM Custom URL Module enables you to create personalized URLs for

I am facing an issue while setting a dependency in the package.json file to a remote beanstalk repository for inclusion in a project. Currently, the setup looks like this: { "name": "SOME_NAME", "version": "0.0.1", "private": true, "dependencies" ...

Developing a NodeJS application with custom Access Control List (ACL)

Recently, I started learning nodeJS and encountered a problem with routing. SiteRoutes.js module.exports = (app, express) => { const router = express.Router(); const Globals = require("../../configs/Globals"); const SiteController = requir ...

Typescript - Troubleshooting undefined error with static variables

My node API app is developed using express and typescript. The static variable of the Configuration Class is initialized with required configuration before starting the server. However, when I try to use this static variable in a separate TypeScript class ...

Encountering a build error message while attempting to install the npm module karma

I am facing an error while attempting to install the Karma NPM module. I am unable to decipher the cause of the error and finding solutions via a Google search has proved unfruitful. Any insights or help on this matter would be greatly appreciated. > ...