chainyjs / chainy

The chainy core + autoloader plugin
https://github.com/chainyjs/chainy/wiki
Other
79 stars 4 forks source link

Chainy data type checking troubles #20

Open mikeumus opened 8 years ago

mikeumus commented 8 years ago

Howdy, I've been trying to do a type check in my data before it runs through a chainy.each() but the way it is now it keeps thinking the data in chainy.set() is the entire object and it doesn't each() through it. However .set(data) was the exact same way I had it written before my type checking so am not sure what's going astray here:

// ... ^

    let Chainy = require('chainy').subclass().require('set feed each');
    let chainyInstance = Chainy.create();

    if (Object.prototype.toString.call(data) === '[object Object]'){
        chainyInstance.set(data);
    } else if (Object.prototype.toString(data) === '[object String]'){
        chainyInstance.set(data).feed();
    }

    chainyInstance
        .each((itemValue, itemIndex, complete) => {
            let name = mpath.get(item_name, itemValue);
            debugger;
            fs.appendFile(path, template(itemValue, name), (err) => {
                if (err) throw err;
                console.log(`The ${name} was appended to file!`);
            });
            complete();
        }).done(function(err, result){
                if (err)  throw err;
                return false; // For testing.
                // console.log('result:', result);  // result: SOME DATA!
        }); 

// ... v

Thanks for any tips. :smiley:

balupton commented 8 years ago

not sure what the exact problem is, however your complete() should be within your appendFile callback, right?

mikeumus commented 8 years ago

That's how I had it originally but it just appended one file and then stopped the loop instead of eaching through.

The problem above is that the each isn't iterating. It's treating the object as a single piece of data instead of iterating through it. Maybe I need to work with complete() here is the issue.

balupton commented 8 years ago
        .each((itemValue, itemIndex, complete) => {
            let name = mpath.get(item_name, itemValue);
            debugger;
            fs.appendFile(path, template(itemValue, name), (err) => {
                if (err)  return complete(err);
                console.log(`The ${name} was appended to file!`);
                return complete();
            });
        }, {concurrency: 0})
balupton commented 8 years ago

For the each issue, check how it works: https://github.com/chainy-plugins/each

Perhaps use .action(function (data) { }) before the .each to modify the data in a way that works with the each

mikeumus commented 8 years ago

Yes I tried it with an action() originally but didn't know how to conditionally execute feed() on the data based on if it were a string or an object.

chainy.set().
.action('currentValue', function(){
 if (typeof data === object){
  return next(null, data.feed());
}

Something like that.