arb / celebrate

A joi validation middleware for Express.
MIT License
1.33k stars 66 forks source link

Custom segments #206

Closed victormoraesgs closed 3 years ago

victormoraesgs commented 3 years ago

Hey there. Is there anyway of working with custom Segments. Currently I am using the express-fileupload node modules to handle file uploads and it creates a req.files property on the express request object.

So, is there any way of extending the Segments so I can have a Segments.FILES working properly?

arb commented 3 years ago

What would you want to validate on req.files? Wouldn't it just be a buffer anyway?

danilomartinssilva commented 3 years ago

What would you want to validate on req.files? Wouldn't it just be a buffer anyway?

There is no Segments.FILES option as an example: Segments.BODY, anyway?

victormoraesgs commented 3 years ago

@arb I do validations like this:

image

In order to try to avoid fake upload requests. The buffer would actually be req.files.file.data, req.files.file is actually an object.

arb commented 3 years ago

Oh I see! Hm... I actually thought about supporting custom segments for a while but it didn't seem like the use case for it ever came up. Currently, there wouldn't be a way to do that unfortunately. Do you have any thoughts on what the public API would look like to support this?

victormoraesgs commented 3 years ago

@arb I thought about providing a helper function called addSegment that would receive two arguments, first the name of the segment and second the actual property name in express request object. i.e

import { Segments, addSegment } from 'celebrate';

addSegment('FILES', 'files');
console.log(Segments.FILES); // Should output 'files'

This would be a starting point IMHO. Also, it would require to change the filename where Segments is defined, since it would not be a constant anymore.

If you give me your blessing I can do it.

arb commented 3 years ago

I'm now remembering why I didn't go down this path. Besides wanting to add segments to validate other parts of req, we'd need to be able to control the order that the different segments are validated in as well. A sane first pass would to do the normal validation, then do all of the "custom" segments next.

arb commented 3 years ago

You really don't need custom segments. What you really need is the ability to add additional steps to the validation pipeline. I could add a steps config option to the opts argument and then append those validation steps to the usual ones. Again, this would be find of limiting because all you could do is the normal validation found here. No conditional checks or anything.

Would writing your own validation of req.files and then creating a celebrate error solve your use case?

arb commented 3 years ago

Closing due to inactivity