Adam W
Adam W

Reputation: 285

Express validation - delegate code in separate file

How can I call the endpoint defined in another file from this router ? this im my router.js file:

const express = require('express');
const { body, validationResult } = require('express-validator');
const router = express.Router();
const validators = require('../validation_files/validation');

// Helper function to handle validation
const handleRequest = (validation, handler) => { 
    return async (req, res, next) => { 
        await Promise.all(validation.map(v => v.run(req)));
    const errors = validationResult(req);
    if (!errors.isEmpty()) { 
        return res.status(400).json({ errors: errors.array() });
    } 
        handler(req, res, next); 
    }; 
};
router.post('/arrived', handleRequest(validators.arrived, (req, res) => {
    //need to call code in arrived.js file, get json response and send response
}));
module.exports = router;

And here is arrived.js file:

const sql = require('mssql'); 
module.exports = function(req, res) { 
    req.app.locals.db.query(
        UPDATE ArriveLog SET {req.body.location} 
    WHERE id=${req.body.placeID},  function(err, result) {
        if (err) {
            console.log(err)  
            res.status(500).send(err')         
        } else { 
            res.status(200).send({'result': true});
        }
    })
}

and this is my validation.js file:

const { body } = require('express-validator');
const validators = {   
    arrived: [
        body('placeID').isInt().withMessage('placeID must be an integer'),
        body('location').isString().withMessage('location must be a string')   
]};
module.exports = validators;

I need to respond either with validation errors or { "result": true} object if all worked ok.

Upvotes: 0

Views: 28

Answers (0)

Related Questions