elasticio / code-component

The holy grail of the elastic.io platform
Apache License 2.0
2 stars 12 forks source link

Code Component Can Not Store State Between Executions #41

Open jhorbulyk opened 4 years ago

jhorbulyk commented 4 years ago

Steps to reproduce

  1. Create a flow: Simple Trigger -> JSONata Transform -> Code JSONata transform:
    [{"one": "foo"}, {"two":"bar"}, {"three": "baz"}]

    Code component:

    let state = {}
    async function run(msg, cfg, snapshot) {
    this.logger.info(`Pre State is: ${JSON.stringify(state)}`);
    state = _.merge(state, msg.body);
    this.logger.info(`Post State is: ${JSON.stringify(state)}`);
    await this.emit('data', { body : {} });
    this.logger.info('Execution finished');
    }

    2.Run the flow once and look at the logs of the code component

Actual Result

The logs contain

Pre State is: {}
Post State is: {"one":"foo"}
Pre State is: {}
Post State is: {"two":"bar"}
Pre State is: {}
Post State is: {"three":"baz"}

Expected Result

The logs contain

Pre State is: {}
Post State is: {"one":"foo"}
Pre State is: {"one":"foo"}
Post State is: {"one":"foo", "two":"bar"}
Pre State is: {"one":"foo", "two":"bar"}
Post State is: {"one":"foo", "two":"bar", "three":"baz"}
jhorbulyk commented 4 years ago

Workaround

The process object is shared between messages

process.state = process.state || {};
async function run(msg, cfg, snapshot) {
    this.logger.info(`Pre State is: ${JSON.stringify(process.state)}`);
    state = _.merge(process.state, msg.body);
    this.logger.info(`Post State is: ${JSON.stringify(process.state)}`);
    await this.emit('data', { body : {} });
    this.logger.info('Execution finished');
}