core icon indicating copy to clipboard operation
core copied to clipboard

my next () does not work | Middleware

Open GlauberF opened this issue 8 years ago • 5 comments

why my next () does not work | Middleware

I know it may be related to async / await, but how could I be writing this code snippet below so that it fucnits correctly.

in my body, I evaluate the field ** isValid **, if it is true I have to give a next and continue with the request, if it is false I send a response 500.

Someone could comment on an example of what this code should look like, thanks

'use strict'

const req = require('request');

class ValidateTokenVimbo {
    async handle({ request, response }, next) {

        const auth = await request.header('authorization');

        async function nexProcess() {
            await next()
        }

        if (auth) {
            req({
                    url: 'https://api-production.site.com.br/v1/validate-token',
                    headers: {
                        "Authorization": auth
                    },
                    method: "GET",
                    json: true
                },
                function(error, response, body) {
                    if (body.isValid) {
                        next()
                    } else {
                    	response.status(500).send('not authorization')
                    }
                });
        } else {
            await response.status(500).send('not authorization')
        }

    }
}

module.exports = ValidateTokenVimbo

GlauberF avatar May 22 '18 20:05 GlauberF

Why are you "awaiting" for request.header? it's already set. I think you should realy think about what are async/await. Rest of your code may not work properly, use await for next in "isValue = true" case.

rewebcan avatar May 22 '18 23:05 rewebcan

Hey @GlauberF! 👋

You need to promisify the call to request. Also, I believe you should learn how async/await work since you are using is in a lot of wrong place.

RomainLanz avatar May 23 '18 08:05 RomainLanz

Okay, how would you write this code @RomainLanz ?

GlauberF avatar May 23 '18 11:05 GlauberF

As he said, you need to brushup your skills with async programming and this issue cannot be used as a way to learn Javascript.

thetutlage avatar May 23 '18 11:05 thetutlage

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

lock[bot] avatar Mar 11 '20 06:03 lock[bot]