2

I'm a begginer in Node.JS and as a first tryout i'm implementing a small url shortening service that will get a request with an id parameter and redirect to the actual url after searching a cassandra database. Below you can find my implementation.

var reqResponse;

app.get('/r/:id', function(req, res) {
    reqResponse = res;
    conn.connect(function(err, keyspace) {
        if(err){
            throw(err);
        }
        conn.cql(cqlSelectStatement, [req.params.id], { gzip:true }, redirectCallback);
    });

});

function redirectCallback (err, results) {
    if (err != null) {
        //log
    } else {
        if (results.length > 0) {
            results.every(function(row){
                reqResponse.writeHead(config.redirectStatus, {
                    'Location': row[0].value
                });
                reqResponse.end();
                return false;
            });
        } else {
            reqResponse.send("There was a problem!");
            return false;
        }
    }
    conn.close();
    return true;
}

It works fine, it does the job, but i'm having some doubts about that reqResponse "global" variable. I don't like it there. Is there a way I could send "res" as a parameter to the redirectCallback function?

Thank you!

maephisto
  • 4,952
  • 11
  • 53
  • 73

1 Answers1

4

Yes there is: Create an anonymous function and use that to pass the parameter:

app.get('/r/:id', function(req, res) {
    conn.connect(function(err, keyspace) {
        if(err){
            throw(err);
        }
        conn.cql(cqlSelectStatement, [req.params.id], { gzip:true }, function (err, results) { redirectCallback(err, res, results); } );
    });

});

And your callback becomes:

function redirectCallback (err, res, results) {
Sonata
  • 2,177
  • 25
  • 32
  • Thanks for this helpful answer - Exactly the same situation as OP - New to JS/Node and really having to rewire my brain. – Denham Coote Feb 13 '15 at 11:30