Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How correctly use Redis with Koa (node.js)

I try to get an information from a redis db and return it as the body of the response to the user. First, here is a code that fails :

var redis = require("redis"),
    koa = require("koa");

var app = koa(),
    port = process.argv[2] || 3000,
    client = redis.createClient();

app.use(function* (next) {

    client.get("test", function (err, res) {
        this.body = res;
    });

    yield next;
});

app.listen(port);
console.log("listen on port " + port)

Surely because the yield calls end before the callback is called.

Then here is a code that success :

function askRedit (callback) {
    client.get("test", callback);
}

app.use(function* (next) {
    this.body = yield askRedit;
    yield next;
});

But I clearly misunderstand why the second one is working. Does the yield in yield askRedit have the same behavior than the one in yield next ?

EDIT : I just seen a page that seems to answers a little : https://github.com/visionmedia/co/blob/master/examples/redis.js

So now I will try to understand these misterious yield.. is this a way of doing synchronous things with asynchronous calls ?

like image 461
AntoineKa Avatar asked Aug 26 '14 00:08

AntoineKa


People also ask

How do I use Redis in node JS?

Create new session. js file in the root directory with the following content: const express = require('express'); const session = require('express-session'); const redis = require('redis'); const client = redis. createClient(); const redisStore = require('connect-redis')(session); const app = express(); app.

How do you implement cache in node JS?

The steps are highlighted below: Spin up a simple Node.js application. Write a reusable custom Redis implementation/cache service. Show how using Redis to cache data from an external API call can help improve the performance of our app.

What is KOA in node JS?

Koa. js is a minimal and flexible Node. js web application framework that provides a robust set of features for web and mobile applications. It is an open source framework developed and maintained by the creators of Express. js, the most popular node web framework.


1 Answers

Here is the correct solution :

"Use strict";

var redis = require("redis"),
    coRedis = require("co-redis"),
    koa = require("koa");

var app = koa(),
    port = process.argv[2] || 3000,
    db  = redis.createClient(),
    dbCo = coRedis(db);

app.use(function* () {
    yield dbCo.set("test", 42);
    this.body = yield dbCo.get("test");
});


app.listen(port);
console.log("listen on port " + port)

theses links helped :

https://github.com/koajs/workshop/tree/master/01-co

http://www.jongleberry.com/koa.html

and "co-redis" of course

Thanks to myself !

like image 86
AntoineKa Avatar answered Sep 30 '22 19:09

AntoineKa