Six six six
Six six six

Reputation: 63

Using redis in an Express route

I want to simply be able to store a value in a key in one route

/api/foo?redisKey="1" (set value for id=1)

then I want to get the value in another route.

/api/bar?redisKey="1" (get value for id=1)

However, redis is async so you have to wait for it to connect

client.on('connect', function() {
    //perform redis operations
});

I'm not sure how to synchronize this in my router.

Upvotes: 0

Views: 1350

Answers (1)

julian soro
julian soro

Reputation: 5228

I am going to assume you're using redis for your client library.

In your express route file, you do not want to create the connection during each request. Instead you will instantiate your redis client outside of the express middleware function, and use it during requests.

Here's a sample app:

var redis = require("redis");
var client = redis.createClient();

var express = require('express')
var app = express()

// GET request
// example: curl "localhost:3000/api/foo?redisKey=1"
app.get('/api/foo', function (req, res) {
  var redisKey = req.query.redisKey

  client.get(redisKey, function (err, reply) {
    if(err){ res.status(400).send(err.getMessage()); return; }
    res.status(200).send(reply.toString())
  });
})

// for setting, use POST request
// example: curl -X POST "localhost:3000/api/foo?redisKey=1&redisValue=helloWorld"
app.post('/api/foo', function(req, res){
  var redisKey = req.query.redisKey,
      redisValue = req.query.redisValue
      // assuming value is also a string in URL query string

  client.set(redisKey, redisValue, function (err, reply){
    res.status(200).send(reply.toString())
  });
})

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

Upvotes: 1

Related Questions