Reputation: 682
I have a bit of a problem with reading the stream from cassandra (I do not even know is it possible what I am trying to achieve). So on the cassandra-driver git repository page there is an example how to use stream. I've tried it and it works.
But however I am trying to use so called classes from ES6 proposal with nodejs 5. I want to define model as a class and in one of the methods I am using stream (where I am fetching the data from cassandra). Problem is with the readable state, where you have this.read() in callback function and now when this is called in a class this becomes a class scope so it is always undefined. I've tried extending my class with the ResultStream from cassandra-driver module but no luck, maybe I am not calling it properly. I've tried with the data state (different class and method as a callback) and it is working since data state has a argument passed as a chunk.
So the question is, how i could encapsulate this stream call in a class method, so the readable state could be read?
Example code of what I would like to achieve:
class Foobar {
constructor(client) {
this.client = client;
this.collection = [];
this.error;
}
getByProductName(query, params) {
this.client.stream(query, params, {prepare: true})
.on('readable', () => {
var row;
while(row = this.read()) { // Problem with this scope
this.collection.push(row);
}
})
.on('error', err => {
if(err) {
this.error = err;
}
})
.on('end', () => {
console.log('end');
});
}
}
Thank you for any advices.
Upvotes: 2
Views: 1846
Reputation: 6600
You could capture the stream
instance in a closure:
class Foobar {
constructor(client) {
this.client = client;
this.collection = [];
this.error;
}
getByProductName(query, params) {
const stream = this.client.stream(query, params, { prepare: true })
.on('readable', () => {
var row;
while(row = stream.read()) { // <- use stream instance
this.collection.push(row);
}
})
.on('error', err => {
if(err) {
this.error = err;
}
})
.on('end', () => {
console.log('end');
});
}
}
Upvotes: 3