Both code and custom components have their use-cases. As a reminder here: code components are handy to write simple one-off, single integration code snippets. If you need to run the same code for multiple integrations, if your code is complex enough that it would benefit from unit testing, or if you are reliant on lots of external Node.JS libraries, consider creating a custom component instead.
Today we'll address a problem that B2B companies often see when working with third-party vendors: data not coming in within an agreed upon spec. Suppose that we and a third-party vendor agreed that we would be sent JSON-formatted data via webhook payload that looked like this:
Our integration worked during testing with sample data, but when we turn on our integration for third-party vendor consumption errors are generated when our integration tries to parse the data that was sent. Logs indicate that the data the vendor is sending is formatted entirely differently than what we agreed to:
The other vendor drags their feet, and claims a fix is a "long ways off". 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! We can fortunately implement a quick fix by adding a code component to the top of our integration to transform the malformed data into the format we expect.
Our integration was written to expect one format of input, but received another. We need to transform the data like this:
into something like this:
That should be pretty easy to do. We really just need to do three things:
- Split the name at the space character to form a first and last name
- Reformat the date of birth into a more reasonable format
- Pull the JSON key ("123") into a value of
If we add a code component to our integration, by default it reads:
Looking at logs, it looks like we've written our destructuring correctly.
Let's next map over the objects (users) that we were sent with
Each iteration of our
map() will generate an object with
We'll reformat the date of birth with the
Date() object, split the name that was provided to us into a first and last name using
split(), and grab the
userid from the keys that were provided to us:
That's it! The rest of our integration can now be configured to reference the results of the code component rather than the body of the integration payload, and it'll start working as we'd expect it to despite the poorly formatted JSON from the third-party vendor. We can see from a test of our code component that our code component is reformatting data like we expect it to: