I'm trying to build a route middleware function to validate a form, but I got a little confused about how should I get errors.
How is validationErrors populated and how should I access it inside route function? The examples I found at the docs and other sites did not helped me
route:
use strict';
const express = require('express');
const router = express.Router();
const User = require('../back/api/models/UserModel');
const Helper = require('./handlerInputs.js');
const bcrypt = require('bcrypt');
router.post('/registrar', [Helper.validaRegistro], function (req, res, next) {
const errors = validationResult(req).throw();
if (errors) {
return res.status(422).json({ errors: errors });
}
[... user register code .... ]
});
handler:
'use strict'
const { check, validationResults } = require('express-validator');
exports.validaRegistro = function(req, res, next){
check(req.body.nome)
.not().isEmpty()
.withMessage('Nome é obrigatório')
.isLength({min: 3, max: 20})
.withMessage('Nome deve ter entre 3 e 20 caracteres')
.isAlpha('Nome deve ser literal');
check(req.body.email)
.normalizeEmail()
.isEmail()
.withMessage('Email inválido');
optPwd = {
checkNull: false,
checkFalsy: false
}
check(req.body.password)
.exists(optPwd)
.withMessage('Senha é obrigatória');
check(req.body.password === req.body.passordconf)
.exists()
.withMessage('Confirme a senha')
.custom((value, { req }) => value === req.body.password)
.withMessage('Senhas não são iguais')
.custom((value, { req }) => value.length >= 8)
const result = req.getValidationResults();
const erros = req.ValidationErrors;
if(erros){
console.log(erros);
}
????
}
What you can do is, Just write validation logic inside middleware itself rather than writing the same thing again and again on the different controller.
Another best way to create common logic is to put validation rules on different files and put handling validation logic in a different file.
Please follow this URL, I have implemented the same thing with efficient way.
https://github.com/narayansharma91/node_quick_start_with_knex
if(erros){
const status = 422;
res.status(status).json({
success: false,
status,
errors: errors.array(),
});
}
Related
I'm playing around with express-validator attempting to apply the .optional method to my request body, but it does not act as I would expect.
I split my sanitization and validation into two files as such:
//common/middlewares/input.sanitization.middleware.js
const { body } = require('express-validator');
exports.patchSanitizationRules = () => {
return [
body('*')
.escape(),
body(['first_name', 'last_name'])
.trim()
.optional(),
body('email')
.trim()
.normalizeEmail()
.optional()
];
};
//common/middlewares/input.validation.middleware.js
const { body, validationResult } = require('express-validator');
exports.validate = (request, response, next) => {
const errors = validationResult(request);
if (!errors.isEmpty()) {
return response.status(422).send({errors: errors});
}
// Checking everything was passed correctly
console.log(request.body);
return next();
};
exports.patchValidationRules = () => {
return [
body()
.notEmpty()
.isLength({min: 4, max: 64}),
body(['first_name', 'last_name'])
.isAlpha()
.optional(),
body('email')
.isEmail()
.optional()
];
};
//users/routes.config.js
const UserController = require('./controllers/users.controller');
const UserSanitizationMiddleware = require('../common/middlewares/input.sanitization.middleware')
const UserValidationMiddleware = require('../common/middlewares/input.validation.middleware');
exports.routesConfig = (app) => {
app.patch('/users/:userId', [
UserSanitizationMiddleware.patchSanitizationRules(),
UserValidationMiddleware.patchValidationRules(),
UserValidationMiddleware.validate,
UserController.patchById
]);
};
So you may already see my issue here. I would like to place .optional into my body() or body('*'). However, doing this will cause whatever field was not in my body to be replaced by "". Now I could add logic in my controller to not allow "" as a valid value, but I would prefer to handle this within my middleware. How can I edit this?
I'm trying to make GET request to external API (Rick and Morty API). The objective is setting a GET request for unique character, for example "Character with id=3". At the moment my endpoint is:
Routes file:
import CharacterController from '../controllers/character_controller'
const routes = app.Router()
routes.get('/:id', new CharacterController().get)
export default routes
Controller file:
async get (req, res) {
try {
const { id } = req.params
const oneChar = await axios.get(`https://rickandmortyapi.com/api/character/${id}`)
const filteredOneChar = oneChar.data.results.map((item) => {
return {
name: item.name,
status: item.status,
species: item.species,
origin: item.origin.name
}
})
console.log(filteredOneChar)
return super.Success(res, { message: 'Successfully GET Char request response', data: filteredOneChar })
} catch (err) {
console.log(err)
}
}
The purpose of map function is to retrieve only specific Character data fields.
But the code above doesn't work. Please let me know any suggestions, thanks!
First of all I don't know why your controller is a class. Revert that and export your function like so:
const axios = require('axios');
// getCharacter is more descriptive than "get" I would suggest naming
// your functions with more descriptive text
exports.getCharacter = async (req, res) => {
Then in your routes file you can easily import it and attach it to your route handler:
const { getCharacter } = require('../controllers/character_controller');
index.get('/:id', getCharacter);
Your routes imports also seem off, why are you creating a new Router from app? You should be calling:
const express = require('express');
const routes = express.Router();
next go back to your controller. Your logic was all off, if you checked the api you would notice that the character/:id endpoint responds with 1 character so .results doesnt exist. The following will give you what you're looking for.
exports.getCharacter = async (req, res) => {
try {
const { id } = req.params;
const oneChar = await axios.get(
`https://rickandmortyapi.com/api/character/${id}`
);
console.log(oneChar.data);
// return name, status, species, and origin keys from oneChar
const { name, status, species, origin } = oneChar.data;
const filteredData = Object.assign({}, { name, status, species, origin });
res.send(filteredData);
} catch (err) {
return res.status(400).json({ message: err.message });
}
};
I am trying to get users data from firebase but I keep receive 'CANNOT GET /' error.
//firebase init
const functions = require('firebase-functions');
const admin = require("firebase-admin");
admin.initializeApp();
//express and cors init
const express = require('express');
const cors = require('cors');
//middleware init
const app = express();
app.use(cors());
const database = admin.database();
app.get("/users", function (request, response) {
return database.ref('/users').on("value", snapshot => {
return response.status(200).send(snapshot.val());
}, error => {
console.error(database);
return response.status(500).send(err);
})
});
exports.users = functions.https.onRequest(app);
I also try to use another function from another website I refer to get at least the username but it returns error.
exports.users = functions.https.onRequest((req, res) => {
database().ref('/merchants').once('value').then(function(snapshot) {
var username = snapshot.val().username;
res.status(200).send(username);
});
});
Problem 1: Exporting express applications
When you export an express app through a Cloud Function, the paths become relative to the exported function name. You exported your app as exports.users which sets the root path of your function to /users and to call it, you would visit https://us-central1-<project-id>.cloudfunctions.net/users.
However, because you defined a route handler for /users (using app.get("/users", ...)) as well, you added a handler for https://us-central1-<project-id>.cloudfunctions.net/users/users instead.
The error Cannot GET / is thrown because when you call the function at https://us-central1-<project-id>.cloudfunctions.net/users, the relative URL is set as "/", which you haven't configured a handler for (using app.get("/", ...)).
So to fix your code above, change
app.get("/users", function (request, response) {
to
app.get("/", function (request, response) {
Problem 2: Username queries
The issue could be as simple as that you call database() instead of admin.database().
However, the purpose of this query is unclear, so I will assume that you have a merchant's ID and you are trying to get the username of the owner of that particular merchant.
This would mean a data structure similar to:
{
"users": {
"somePerson": { ... },
"otherPerson: { ... }
},
"merchants": {
"reallyGreatGuyInc": {
"username": "somePerson",
...
},
"realShadyPeopleInc": {
"username": "otherPerson",
...
}
}
}
If you exported a function called getMerchantUsername where you pass in the merchant ID via a GET parameter and call it at the URL https://us-central1-<project-id>.cloudfunctions.net/getMerchantUsername?id=reallyGreatGuyInc, you would define it using the following code:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.getMerchantUsername = functions.https.onRequest((req, res) => {
if (!req.query.id) {
// '?id=' is required
return res.status(400).send("Missing 'id' parameter");
} else if (/[\u0000-\u001F\u007F\.\$#/\[\]\\]/.test(req.query.id)) {
// check id for invalid characters
return res.status(400).send("Invalid 'id' parameter");
}
// run query
admin.database().ref(`/merchants/${req.query.id}/username`).once('value')
.then((snapshot) => {
var username = snapshot.val();
res.status(200).send(username);
})
.catch((error) => {
console.error(error);
res.status(500).send('Request failed.');
});
});
Notes:
The test for invalid characters is based on the list in the RTDB: Structure data documentation. This somewhat prevents looking at other database values.
If you only need the value of username, rather than request the entire merchant object and parse it, request only the username as in the example above where I used `/merchants/${req.query.id}/username`.
I'm stuck on how to design error handling in an Express.js application.
What are the best design practices to handle errors in Express?
To my understanding, I can handle errors in 2 different ways:
First way would be to use an error middleware and, when an error is thrown in a route, propagate the error to that error middleware. This means that we have to insert the logic of the error handler in the middleware itself (note, the middleware here was purposely kept simple).
app.post('/someapi', (req, res, next) => {
if(req.params.id == undefined) {
let err = new Error('ID is not defined');
return next(err);
}
// do something otherwise
});
app.use((err, req, res, next)=>{
// some error logic
res.status(err.status || 500).send(err);
});
Another option is to deal with the errors on the spot, when the error happens. This means that the logic must be in the route itself
app.post('/someapi', (req, res, next) => {
if(req.params.id == undefined) {
let err = new Error('ID is not defined');
// possibly add some logic
return res.status(ErrorCode).send(err.message);
}
// do something otherwise
});
What is the best approach, and what are the best design practices for this?
Thank you
I think there are much more extensive cases but the main idea is using middleware design. Add your validation logic to this middleware.
yourRouter.post('/message', routerValidator.messageValidator, yourController.saveMessage.bind(yourController));
Below is my sample structure;
// controller
const BaseRoute = require('../infra/base/BaseRoute');
const log = require('./../../utils/log-helper').getLogger('route-web');
const { ErrorTypes } = require('../infra/middlewares/ErrorMiddleware');
const GameService = require('../../service/GameService');
const { SystemMessages } = require('../../statics/default_types');
module.exports = class WebController {
constructor() {
this._logger = log;
this._gameService = new GameService();
}
getGameInfo(req, res) {
var self = this;
try {
const info = self._gameService.getGameInfo(req.body.query);
return BaseRoute.success(res, { info });
} catch (err) {
self._logger.error('Something went wrong while getting game information', err);
return BaseRoute.internalError(res, SystemMessages.GENERIC_ERROR, req.getErrorCode(ErrorTypes.UNHANDLED, 1));
}
}
};
// router index
const express = require('express');
const ErrorMiddleware = require('../infra/middlewares/ErrorMiddleware').ErrorMiddlewarePath;
const baseValidator = require('../infra/validators/BaseRouterValidator');
const AndroidController = require('./AndroidController');
const IosController = require('./IosController');
const WebController = require('./WebController');
const AndroidRouter = express.Router();
const IosRouter = express.Router();
const WebRouter = express.Router();
const androidController = new AndroidController();
const iosController = new IosController();
const webController = new WebController();
AndroidRouter.post('/message', ErrorMiddleware(1), baseValidator.teamQueryValidator, androidController.getGameInfo.bind(androidController));
IosRouter.post('/message', ErrorMiddleware(1), baseValidator.teamQueryValidator, iosController.getGameInfo.bind(iosController));
WebRouter.post('/message', ErrorMiddleware(1), baseValidator.teamQueryValidator, webController.getGameInfo.bind(webController));
module.exports = {
AndroidRouter,
IosRouter,
WebRouter
};
// validator
const log = require('../../../utils/log-helper').getLogger('route-validator-base');
const BaseRoute = require('../base/BaseRoute');
const _ErrorTypes = require('../middlewares/ErrorMiddleware').ErrorTypes;
function teamQueryValidator(req, res, next) {
if (!req.body || !req.body.query) {
const params = req.body ? JSON.stringify(req.body) : 'Empty';
log.error('Invalid Parameters req body', params);
return BaseRoute.httpError(res, 'Bir takım adı giriniz..', 400, req.getErrorCode(_ErrorTypes.VALIDATION, 1));
}
return next();
}
module.exports = {
teamQueryValidator
};
// app.js that assigns to express
this._router = require('./src/route/api/index');
this._ErrorMiddleware = require('./src/route/infra/middlewares/ErrorMiddleware').ErrorMiddlewareRouter;
this.app.use('/api/android', this._ErrorMiddleware(1), this._router.AndroidRouter);
this.app.use('/api/ios', this._ErrorMiddleware(2), this._router.AndroidRouter);
this.app.use('/api/web', this._ErrorMiddleware(3), this._router.WebRouter);
What are the best design practices to handle errors in Express?
There is no best design, it's all subjective.
To my understanding, I can handle errors in 2 different ways:
Correct. You used error middleware for the first and then handled the error directly in the route handler.
To me, it makes sense to separate out the error handling logic from the business logic. It makes for cleaner code. So the former (error middleware) would be better IMO.
You would have a different error handler for different errors.
I'm using the latest version of express-validator for validation.
I'm not getting any response, However Old method i.e checkBody is working fine while new method i.e check('keyName') is not working properly.
Below is my code.
package.json
"express-validator": "^5.0.3",
routes.js
var authValidator = require('./../validation/auth.validation');
var routes = require('express').Router();
routes.post('/login', [
authValidator.validateLogin,
authValidator.checkValidationResult ], function (req, res) {
console.log('3');
//res.send("Some other stuffs");
}
);
module.exports = routes;
auth.validation.js
module.exports.validateLogin = validateLogin;
module.exports.checkValidationResult = checkValidationResult;
const {check, validationResult} = require('express-validator/check');
const {matchedData, sanitize} = require('express-validator/filter');
var response = require('./../general/MyResponse');
var messages = require('./../general/messages');
function validateLogin(req, res, next) {
console.log('1');
return [
check('email').isLength({min: 1}).withMessage(messages.EMAIL_REQUIRED)
.isEmail().withMessage(messages.INVALID_EMAIL),
check('password').isLength({min: 1}).withMessage(messages.PASSWORD_REQUIRED),
]
}
function checkValidationResult(req, res, next) {
console.log('2');
var result = validationResult(req)
if (!result.isEmpty()) {
response.createResponse(
res, 400,
result.array()[0].msg,
{'error': result.array()[0].msg}, {}
)
} else {
next()
}
}
I've noticed that node js not able to go ahead from the function validateLogin in auth.validation.js.
Can anyone tell me what's wrong with above code.
Inside console, Only 1 is displaying.
I'm attaching screenShot for referance.
We need to use simple Array and don't need to create function.
Follow this link
Is it possible to do the validation in a separate file and not inline in the route? - GitHub for more details.
Code should be like this.
auth.validation.js
var response = require('./../general/MyResponse');
var messages = require('./../general/messages');
const {check, validationResult} = require('express-validator/check');
const {matchedData, sanitize} = require('express-validator/filter');
module.exports.validateLogin = [
check('email').isLength({min: 1}).withMessage(messages.EMAIL_REQUIRED).isEmail().withMessage(messages.INVALID_EMAIL),
check('password').isLength({ min: 1 }).withMessage(messages.PASSWORD_REQUIRED),
];
module.exports.checkValidationResult = checkValidationResult;
function checkValidationResult(req, res, next) {
console.log('2');
var result = validationResult(req)
if (!result.isEmpty()) {
response.createResponse(res, 400,
result.array()[0].msg,
{'error': result.array()[0].msg}, {}
)
} else {
next()
}
}
`
validateLogin and checkValidationResult are being applied as middlewares to your route. In middlewares you use next()method to call next middleware in the queue. Just like in your checkValidationResult.
In case of validateLogin, its not passing control to next middleware. But check method from express-validator v5 is itself a middleware method. Thus I guess it won't work correctly.
Please have a look at: https://github.com/ctavan/express-validator/issues/449
Try using following Code:
routes.js
var authValidator = require('./../validation/auth.validation');
var routes = require('express').Router();
var authValidations = authValidator.getAuthValidations();
routes.post('/login',
authValidations,
authValidator.checkValidationResult, function (req, res) {
console.log('3');
//res.send("Some other stuffs");
}
);
module.exports = routes;
auth.validations.js
module.exports.getAuthValidations = getAuthValidations;
module.exports.checkValidationResult = checkValidationResult;
const {check, validationResult} = require('express-validator/check');
const {matchedData, sanitize} = require('express-validator/filter');
var response = require('./../general/MyResponse');
var messages = require('./../general/messages');
function getAuthValidations(req, res, next) {
return [
check('email').isLength({min: 1}).withMessage(messages.EMAIL_REQUIRED)
.isEmail().withMessage(messages.INVALID_EMAIL),
check('password').isLength({min: 1}).withMessage(messages.PASSWORD_REQUIRED),
]
}
function checkValidationResult(req, res, next) {
console.log('2');
var result = validationResult(req)
if (!result.isEmpty()) {
response.createResponse(
res, 400,
result.array()[0].msg,
{'error': result.array()[0].msg}, {}
)
} else {
next()
}
}