Prismatic is currently in private beta! Request beta access
Photo of Taylor Reece
Taylor Reece, Developer Advocate
August 04, 2020 • 6 min read

Using the Code Component to Add Short Custom Code Snippets to Integrations

Prismatic's code component lets you incorporate custom JavaScript code anywhere in your integration. While Prismatic's built-in components save you time and code by handling a significant portion of your integration logic, B2B software teams frequently run into product- or industry-specific or other "non-standard" integration requirements that call for some custom code.

In my previous post I noted that there were two methods that Prismatic provides for incorporating custom code into your integrations: you can either build a custom component, or add short code snippets using the code component. These are both helpful if your integration requires product-specific or industry-specific business logic that can't be solved using built-in components.

In that post, we looked at writing reusable custom components with Prismatic's custom component library and went over the reasons you should choose a custom component or code component. To recap, you should write a custom component if:

  • Your code requires Node.js libraries that are not included in the code component environment.
  • Your code is complex enough to merit unit testing.
  • You intend to reuse your custom code in multiple integrations.
  • You are writing multiple related actions that share code, and you would like to bundle those actions together into one cohesive package.

On the flip side, if you have a problem in a single integration that can be solved with a few lines of JavaScript, you're probably better off writing a short snippet using a code component instead. Code components can be be quickly added to an integration - just a couple of clicks within the web app and you'll be ready to code.

In this post, let's take a look at a couple of code component use cases, and examine how code component snippets can reference previous steps' outputs, write log lines, and return values that subsequent steps can consume.

Scenario 1: The Uncooperative Third-Party Vendor

How often has it happened that you and the vendor whose software you're integrating with agreed to some standard of communication, and then the other vendor didn't come close to adhering to your agreed upon plan? In this first example, suppose that a third-party vendor agreed to send us user data as a JSON-formatted list of objects like this:

[
  {
    "firstName": "John",
    "lastName": "Smith",
    "dob": "1987-05-20",
    "userid": "123"
  },
  {
    "firstName": "Jane",
    "lastName": "Smith",
    "dob": "1992-07-16",
    "userid": "172"
  }
]

But, when we turn our integration on it errors out when it tries to parse data that the vendor is sending to us. Logs show that the data the vendor is sending is formatted entirely different than what we agreed to:

{
  "123": {
    "name": "John Smith",
    "dob": "05/20/1987"
  },
  "172": {
    "name": "Jane Smith",
    "dob": "07/16/1992"
  }
}

Further, when we call the third-party vendor out on their mistake, they finger-point, drag their feet, and eventually agree that they can deploy a fix... maybe in quarter 3 of this year (or quarter 1 of next year... they'll at least "get it on their roadmap"...).

We don't have time to wait for the other vendor to fix their software - our customer is clamoring for the new integration they paid for! Luckily the data our integration is receiving is easily salvageable using a code component. With a few lines of JavaScript we should be able to transform what they're sending us into the format we developed our integration to handle:

module.exports = async (context, params) => {
  const data = params.trigger.all.body;
  return Object.keys(data).map((key) => {
    dob = new Date(Date.parse(data[key]["dob"]));
    return {
      firstName: data[key]["name"].split(" ").slice(0, -1).join(" "),
      lastName: data[key]["name"].split(" ").slice(-1).join(" "),
      dob: dob.toISOString().slice(0, 10),
      userid: key,
    };
  });
};

Now, what is this code doing? Code components expect you to export a function. So, our first line is exporting an anonymous function that takes two parameters, context and params. context gives us a logging tool and some information about config vars - we can ignore that for this code component. params allows us to grab outputs from previous steps in the integration - that's useful for our integration.

The second line (const data = params.trigger.all.body) loads up the data that the other vendor sent to our integration via the integration's webhook trigger.

The return section splits users' first and last names into distinct strings, converts date format, and moves the user's ID from being a key to being a value in the user object, so that something like this:

"123": {
  "name": "John Smith",
  "dob": "05/20/1987"
}

Is turned into something like this:

{
  "firstName": "John",
  "lastName": "Smith",
  "dob": "1987-05-20",
  "userid": "123"
}

Here, we can see on the bottom left that our code component is outputting data in the format we need, and we can move on with our integration implementation without having to wait for the other vendor to fix their code:

Screenshot of third party integration code component

Scenario 2: Parsing Email Addresses

For our next scenario, suppose we have been tasked with writing an integration that periodically pulls down a web page and scrapes the contents of the page for email addresses that are then imported into our software. Prismatic provides the built-in HTTP component for pulling down web page contents. All that's left to do is parse out email addresses. We can throw a little regex into a code component to make short work of this task:

module.exports = async (context, { get_webpage: { all: webPageContents } }) => {
  const emailRegex = /([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi;
  const emailAddresses = [...new Set(webPageContents.match(emailRegex))];
  context.logger.info(`Found ${emailAddresses.length} email addresses.`);
  return emailAddresses;
};

Like the previous scenario, this code component exports a single function that takes two arguments. Let's look at another way of referencing param - this time lets use JavaScript destructuring to reference output of a previous step named get_webpage , and save the contents of the web page to a variable named webPageContents. We could have instead used async (context, params) notation like in the previous scenario, and then grabbed website contents with webPageContents = params.get_webpage.all. Either works, but most JavaScript devs I know sure love destructuring!

We can then use the regex .match() function to extract email addresses, and a Set() object to ensure that we don't capture duplicate email addresses.

The fourth line of our function that starts with context.logger.info uses Prismatic's built-in logging functionality to write out a log line. We can see that log line in the Testing pane of the integration designer on the bottom right, and the email addresses that the code component scraped can be seen as outputs of the step on the bottom left:

Screenshot of scraping emails code component

Done! With just a half-dozen line code snippet in a code component we have a functioning email scraper integration!

Learn More

These were just a couple scenarios where the code component comes in handy. While Prismatic's built-in components save time by handling much of your integration logic right out of the box, code components ensure you never get stuck. You can always build exactly the functionality you need, no matter how product-specific, industry-specific, or otherwise "out of the box" your integration scenario may be.

For additional information on the code component, including how to interact with configuration variables, see our Code Component Usage article. Another example of a code component in action is available in our Writing an Integration in YAML quickstart.

To learn more about how Prismatic can help you more easily handle any integration scenario, request beta access or reach out - we'd love to chat!


About Prismatic

Prismatic is the dev-first integration platform for B2B software companies and the easiest way to build, deploy, and support integrations. A complete toolkit for the whole organization, Prismatic includes an integration designer, testing framework, customer deployment management, logging, monitoring, alerting, and an embeddable customer integration portal. Prismatic is a solution for the real world, designed to handle messy, complex integration scenarios and work with existing toolchains. Flexible and extensible, Prismatic empowers teams to tackle bespoke and vertical-specific integrations between applications of all kinds, SaaS or legacy, with or without a modern API, regardless of protocol or data format. Born out of its founders’ experience scaling a software company with hundreds of unique integrations, Prismatic aims to help teams spend less time on integrations and more time driving core product innovation. Learn more at prismatic.io.

Get the latest from Prismatic

Subscribe to receive updates, blog posts, and more. You'll be the first to know when we launch!

You can unsubscribe at any time.