Building/Passing input and 2 outputs for small JavaScript function

Guys, learning how to use the JS flow function.
But not sure how to “connect” the input data (a list of objects with 15 properties) to

function countTokensPerCurrency (data)


The function does not seem to fire after my get collection record flow function.

Hi,

All inputs are passed inside an inputs object, so to reference your data, you need to use:

inputs.data

Instead of just data. Also, returning the result shall be done by putting the data into one of the outputs. Read more here:

1 Like

Thanks, fixed the input.
Seems I need t adjust the outputs definition in the script too since there’s no return?
image

function countTokensPerCurrency(inputs) {
  const data = inputs.data;
  const result = {};
  let error = null;

  try {
    data.forEach(item => {
      if (!result[item.currency]) {
        result[item.currency] = [];
      }
      item.services.forEach(service => {
        service.category.forEach(tokenObject => {
          const token = tokenObject.token;
          const existingToken = result[item.currency].find(item => item.token === token);
          if (existingToken) {
            existingToken.count++;
          } else {
            result[item.currency].push({token, count: 1});
          }
        });
      });
    });
  } catch (e) {
    error = "error";
  }
  return error ? [1, error] : [0, result];
}

Hi,

result - is an object as well, so you need to pass the result correctly. Here is a basic example from a fresh JS flow function, where result is an object with 1 property.

return { result: inputs.input1.toUpperCase() };

You should check the outputs in the JavaScript flow function directly.

1 Like

For our readers (since I find your documentation on custom JS a bit light), here is the right syntax for return, given that result and error are objects:

return error ? [1, {error}] : [0, {result}]

[0] is the index for the first output (first ‘success’ node)
[1] is the index for the second output (second ‘fail’ node)

Example of 2 outputs matching the script further above:



1 Like