TaoJS
TaoJS

Reputation: 119

Increment id and assign it to string using ioredis for redis database

I work on a blog using redis and I got stuck at the api level. I'm trying to do the following thing:

MULTI
INCR id
SET post:{id} json_value //Stucked here
SADD posts {id}
EXEC

So how do I get the id for the SET post:{id}?

I have the following code for now which doesn't work yet.

// Create post
function cpost(json) {
    client.pipeline()
        .incr('id'))
        .set('post:' + client.get('id:post', function (err, results) {
            return results;
        }), json)
        .sadd('posts, client.get('id:post', function (err, results) {
            return results;
        })) // posts post
        .exec(function (err, results) {

    });
}

Using ioredis

Any ideas on how to get the value of the id?

Upvotes: 1

Views: 2412

Answers (2)

Maia
Maia

Reputation: 31

If you want to have a transaction you should be using multi() instead of pipeline() (I think that's the case).

Below is the way I dealt with this problem.

I could only do this in two steps using promises. You can also achieve the same using callbacks. Either way the increment is out of the transaction or batch.

function cpost(json) {
    client.incr('id', 'post').then(function (postId) {
        client.multi()
            .set('blog:post:' + postId, json)
            .sadd('blog:posts', postId)
            .exec()
            .then(
                function onSuccess(data) {
                    // success handling goes here
                },
                function onError(data) {
                    // error handling goes here
                }
            );
}

Upvotes: 3

TaoJS
TaoJS

Reputation: 119

I don't think this is the right way to solve my problem, but I have to move on. Simplest solution ever (counter):

var id = 0;
function cpost(json) {
    id++;
    client.pipeline()
        .incr('id', 'post')
        .set('blog:post:' + id, json) // blog:post:1
        .sadd('blog:posts', id) // blog:posts id:post
        .exec(function (err, results) {
    });
}

Upvotes: 1

Related Questions