A code component forked from the elastic.io code-component, runs a piece of a JavaScript code inside your flow.
Here are the available variables and libraries that can be used within the context of execution. The most up-to-date list
can always be found in be used within the context of execution or in code.js
of the component. Below is a sample for the reference.
Built-in Node.js global objects are also supported.
msg
- incoming message containing the payload from the previous stepcfg
- step's configuration. At the moment contains only one property:code
(the code, being executed). May contain further attributes passed through thefields
propery in the flow definitionsnapshot
- step's snapshotmessages
- utility for convenient message creationemitter
user to emit messages and errors
wait(numberOfMilliscondsToSleep)
- Utility function for sleepingrequest
- Http Client (wrapped inco
- this library so that it is pre-promisified)_
- Lodash
Use code is very simple, just do following:
async function run(msg, cfg, snapshot) {
this.logger.info('Incoming message is %j', msg);
const data = { result : 'Hello world!' };
// You can emit as many data messages as required
await this.emit('data', { data });
this.logger.info('Execution finished');
}
Please note if you have a simple one-in-one-out function you can simply return a JSON object as a result of your function, it will be automatically emitted as data.
JSONata is great however sometimes it's easier to do things in JavaScript, if you want to transform an incoming message with code, just use following sample:
async function run(msg, cfg, snapshot) {
return {
addition: 'You can use code',
keys: Object.keys(msg)
};
}
It's very simple to code a small REST API call out of the Code component, see following example:
async function run(msg, cfg, snapshot) {
const res = await request.get({
uri: 'https://postman-echo.com/get?foo1=bar1&foo2=bar2',
json: true
});
return {
arguments: res.body.args
}
}