-
-
Notifications
You must be signed in to change notification settings - Fork 616
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Validation as middleware too distant from dependent code? #1187
Comments
Hey @jallen-cse
'I feel that performing validation with middleware causes the validation code to be far away from the code that relies upon the validation.' |
It's my fault for asking this poorly, I omitted the result call in my example. I meant that the validation logic is not anywhere near the consuming logic in the controller. From a maintenance perspective, I feel this is unsafe. If the controller's requirements change, you must be sure that the validation logic (located elsewhere) is changed accordingly.
I don't mean to be argumentative, but this is simply an assertion that I am questioning in the original post. |
I understand your frustration @jallen-cse 😕 Unfortunately even There's no way, at the moment, for express-validator to infer the types when returning you the data that you validated. Something I've been thinking about is to have a single middleware that holds all the validations, and you can also invoke functions like type UserData = { name: string, age?: number, /* etc etc */ };
const userValidator: Validator<UserData> = createValidator(
body('name').notEmpty(),
body('age').optional().isInt({ min: 18 }),
);
app.post('/user', userValidator, (req, res) => {
try {
const data: UserData = userValidator.getData(req);
} catch (e) {
// invalid request
}
}); |
I had same issue. I checked
|
Try something like this, it might work
|
@soham0005 |
Hello all,
I am relatively new to express validator. I have been trying it out in development of a simple RESTful interface. My project is organized into the conventional [routes, controllers, services] structure.
I feel that performing validation with middleware causes the validation code to be far away from the code that relies upon the validation. This worries me from a maintenance standpoint.
An example:
then
In other cases (like for query parameters), if we are using TypeScript, we still have to break the safety and coerce into our sanitized, validated type.
I have thought about validating imperatively as mentioned in the docs, but that doesn't help with the TypeScript stuff.
Does anyone have any recommendations / solutions to these two concerns? Maybe I'm just missing something here.
Thanks in advance.
-Jack
The text was updated successfully, but these errors were encountered: