Skip to content

Instantly share code, notes, and snippets.

@phoenixbox
Last active November 19, 2021 17:55
Show Gist options
  • Save phoenixbox/9468bcde1641bd977bd564259b1b4d0e to your computer and use it in GitHub Desktop.
Save phoenixbox/9468bcde1641bd977bd564259b1b4d0e to your computer and use it in GitHub Desktop.
PriceBlocs - Zapier Run JS - Process form data
// this is wrapped in an `async` function
// you can use await throughout the function
const OBJECT_NEWLINE_DELIMETER = "\n\n";
const FIELD_NEWLINE_DELIMETER = "\n";
const KEY_DELIMETER = ": ";
const COMPLEX_VALUE_FIELD_TYPES = ["tin"];
const extractComplexValue = (data) => {
const stringObj = data.value.replace(/ /g, "").replace(/'/g, '"');
try {
return JSON.parse(stringObj).value;
} catch (error) {
return "";
}
};
/**
* e.g. value: {'code': 'US'} -> {'code': 'US'}
*/
const removeKeyFromField = (key, field) => field.replace(new RegExp(`^${key}${KEY_DELIMETER}`), "");
const convertResponseToObject = (response) =>
response.split(FIELD_NEWLINE_DELIMETER).reduce((memo, field) => {
const fieldParts = field.split(KEY_DELIMETER);
const key = fieldParts[0];
if (key === "value") {
memo[key] = removeKeyFromField(key, field);
} else {
memo[key] = fieldParts[1];
}
return memo;
}, {});
/**
* 1. Set formData on global inputData from within Zapier UI
* 2. Then within this code block we pick it off the global inputData object
* 3. Split it with the double new line delimeter to group the form data responses
* 4. Convert the response string into a workable JS object
* 5. Handle extra value formatting for complex input types like tin (tax identification number)
* 6. Return the form data as a keyed object and NOT an array
*/
const responses = inputData.formData.split(OBJECT_NEWLINE_DELIMETER);
const formData = responses.map((response) => {
const responseObject = convertResponseToObject(response);
const hasComplexValue =
COMPLEX_VALUE_FIELD_TYPES.indexOf(responseObject.uid) > -1;
if (hasComplexValue) {
responseObject.value = extractComplexValue(responseObject);
}
return responseObject;
});
output = { formData };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment