h0x91b / redis-fast-driver

78 stars 13 forks source link

Convert response to readable stream #48

Open fsfarah opened 3 years ago

fsfarah commented 3 years ago

First off, thank you for this amazing library!

The following snippet adds a streamCall method, it emits data. The data event is used to feed a readable stream. I don't know who else might find this interesting... I had a use case and thought of sharing it.

Is this the best method for doing so? Is there any more direct way for converting the output to a readable stream?

const { Readable } = require('stream');

const Redis = require('redis-fast-driver');

const r = new Redis({
    host: '127.0.0.1', //can be IP or hostname
    port: 6379,
});

const redisStream = new Readable({
    read() {
        r.once('data', data => {
            if (data === null) {
                this.push('null') // avoid stream close
            } else {
                this.push(data)
            }
        })
    },
    objectMode: true
});

r.streamCall = (command) => {
    return r.rawCall(command, (err, resp) => {
        if (err) r.emit('error', err);
        else r.emit('data', resp);
    });
}

redisStream.on('data', data => {
    console.log(data);
});

r.streamCall(['del', 'mylist']);
r.streamCall(['rpush', 'mylist', [1, 2, 3, 4]]);
r.streamCall(['lrange', 'mylist', 0, -1]);
r.streamCall(['del', 'foo']);
r.streamCall(['set', 'foo', 'bar']);
r.streamCall(['del', 'none']);
r.streamCall(['get', 'none']);
setTimeout(() => {
    r.streamCall(['get', 'foo']);
}, 100);