Making node code's results available as objects in subsequent steps

Here is my code:

import { axios } from "@pipedream/platform"; 
// To use previous step data, pass the `steps` object to the run() function
// Assuming `steps.trigger.event.body` is the incoming payload
// Get the body from the trigger step
async function run({ steps }) {
  // Get the body from the trigger step
  const originalBody = steps.trigger.event.body;

  try {
    // Stringify and parse the JSON to ensure it's valid
    const formattedBody = JSON.stringify(originalBody, null, 2); // Beautified JSON string
    const validJSON = JSON.parse(formattedBody); // Will throw an error if not valid JSON
    
    // Set the export using the 'this' keyword
    this.validJSON = validJSON;
  } catch (e) {
    console.error('Invalid JSON:', e);
    // Handle the error appropriately, maybe stop the workflow or notify you
    this.error = e.message;
  }
}

I want to use validJSON as the body for a POST to an API.

But I have not been able to access it. It doesn’t show up as an export.

Hi @Timfong888,

It looks like you’re trying to use the validJSON variable in another step, but it’s not being exported correctly. To fix this issue, you should use a Pipedream component and return the validJSON value from the run method. Here’s the updated code:

import { axios } from "@pipedream/platform";

export default defineComponent({
  async run({ steps, $ }) {
    const originalBody = steps.trigger.event.body;

    try {
      const formattedBody = JSON.stringify(originalBody, null, 2);
      const validJSON = JSON.parse(formattedBody);
      return validJSON;
    } catch (e) {
      console.error('Invalid JSON:', e);
      this.error = e.message;
    }
  },
});

Now, the validJSON value will be exported and can be accessed in the next step using steps.<step_name>.$return_value, where <step_name> is the name of the step containing the above code.
I’m a bot powered by Pipedream and GPT-4. I’m still learning, so please double check my answers and code! Learn how to build your own.

1 Like