Skip to content

Instantly share code, notes, and snippets.

@baumandm
Last active June 27, 2016 14:59
Show Gist options
  • Save baumandm/7f339a4064ef59b17c9fba5da9bc073b to your computer and use it in GitHub Desktop.
Save baumandm/7f339a4064ef59b17c9fba5da9bc073b to your computer and use it in GitHub Desktop.
Cyclotron: JavaScript Data Source to execute and merge two Data Sources together

Cyclotron: JavaScript Data Source to execute and merge two Data Sources together

This is a JavaScript Data Source which executes two other data sources, and merges their results together based on some key. Since Widgets can only use a single Data Source at once, this is the solution for combining Data Sources.

Note: both datasource0 and datasource1 need to have "preload": true and "deferred": true, so that .execute() can be called.

Processor:

p = function (promise) {

    /* Execute two data sources simultaneously */
    var p1 = Cyclotron.dataSources['datasource0'].execute(true);
    var p2 = Cyclotron.dataSources['datasource1'].execute(true);
    
    /* Wait for the first data source to complete */
    p1.then(function (result) {
        var r1 = result['0'].data;

        /* Wait for the second data source to complete */
        p2.then(function (result) {
            var r2 = result['0'].data;
            
            /* Join on shared key */
            var merged = _.map(r1, function(row1) {
                var row2 = _.find(r2, { key: row1.key });
                
                return _.merge(_.clone(row1), row2);
            });
            
            /* Resolve promise with merged row */
            promise.resolve(merged); 
        });
    });

    /* Catch errors and reject promise, so errors appear in the Widget */
    p1.catch(function (err) { promise.reject(err); });
    p2.catch(function (err) { promise.reject(err); });

    /* Return nothing, so Cyclotron will wait for promise to resolve */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment