19

Debugging Multer and other middle-wares

 2 years ago
source link: https://dev.to/bacloud14/debugging-multer-and-other-middle-wares-3d2
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
bacloud14

Posted on Dec 2

Debugging Multer and other middle-wares

I've been sipping coffee, rolling cigarettes, and pulling my hair since the day before yesterday.

I have trouble setting what I thought a useful dynamic middle-ware for later implementations. (Post request with so much constraints, now and surely in future).

The issue is with Multer (or connect-sequence see later). If you know, Multer is a Node.js middleware for handling (including parsing) multipart/form-data.

What I expect could differ though and this is why I'm setting this super intelligent middle-ware.

I found how to chain middle-wares on runtime, which is not a very usual task, but possible and very useful for my case:

connect-sequence

The solution dates a bit as you can see. Anyway, here is a slice of my middle-ware code (that constructs and runs other middle-wares in return).

async function magicMiddleware(req, res, next) {
    const contentType = req.get('content-type')
    const form = formidable({})

    if (contentType.indexOf('multipart/form-data') > -1) {
        await form.parse(req, function (err, fields, files) {
            if (err) {
                console.log(String(err));
                return;
            }
            magicMiddleware_(fields)
        })
    } else {
        magicMiddleware_(req)
    }

    const section = req.params[0]
    const method = req.method

    const magicMiddleware_ = (body) => {
        const {
            secured,
            upload,
            geolocation,
            illustrations,
            schema
        } = constraints[process.env.NODE_ENV][method][section]
        singletonSchema = schema()

        // Third party middlewares
        var seq = new ConnectSequence(req, res, next)
        debugger;
        const validating = celebrate({
            [Segments.BODY]: singletonSchema,
        })
        if (upload) { 
            console.log('attaching multer')
            seq.append(ops.multer) 
        }
        if (!singletonSchema.called) {
            seq.append(validating)
        }
        seq.append(errors())
        if (secured) { 
            console.log('attaching multer')
            seq.append(ops.auth0) 
        }
        seq.run()
        console.log(req.body)
    }
}

Enter fullscreen mode

Exit fullscreen mode

It is to know that third party middle-wares could mismatch. One adds something to req and one remove the same thing for instance.

I run debugger and couldn't find out but I think multer specifically is not running well, It is running but not well; req.body is {}, not undefined and not anything else.

I put multer at first in the sequence to be able to parse multipart/form-data data I'm testing right now, then there is celebrate (Joi based validation middle-ware). Then there is auth0 too (for passwordless authentication).

Of course there are multiple application middle-ware attached when the app starts. But none is susceptible of causing harm as if I push multer, celebrate and auth0 as middle-wares directly (as usual), all works fine.

So data is parsed, req.body is there with the uploaded file and input text fields.

I'm pulling my hair, really. As I don't want to cancel all this and start from zero pushing middle-wares directly on multiple post requests (with different constraints: like one runs without authentication, the other expects text/plain all combinations might behave differently on different environments, like no upload when testing with Postman).

If you have a hint, I will follow up with test. If you want to jump on code, here is the file and here is the repo.

Note: there is a bug in connect-sequence. It is expecting err (passed through next(err)) to be different that undefined. But Multer appears to push null when there is no error. So there is this, I modified code accordingly.

From this:
if (err !== undefined) {

To this:
if(err)

Final note: I want to believe in in connect-sequence as I couldn't find my way adding middle-wares at runtime. I went through code (not debugging) and all seems well to my eyes.

Thanks a lot !!!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK