Skip to content

Instantly share code, notes, and snippets.

@devilelephant
Last active April 17, 2018 19:24
Show Gist options
  • Save devilelephant/5c6fb441842bd2d873386045ff672ab1 to your computer and use it in GitHub Desktop.
Save devilelephant/5c6fb441842bd2d873386045ff672ab1 to your computer and use it in GitHub Desktop.
Json Tranform Lambda

JsonTransform

Transform Json Input

function input

Use a Pass type Step Function to merge a script under the field name "transformScript into the input JSON.

"Inject Update Status and Updated": {
  "Type": "Pass",
  "Result":"event.doc.status = event.jobStatus.success ? 'finished' : 'failure'; event.doc.updated=new Date()"
  "ResultPath": "$.transformScript",
  "Next": "..."
}

The script can modify the 'event' object containing the parsed input json, which will be returned as the output of the lambda.

In the example above the script adds the following to the input.

"doc": {
    "status": "finished",
    "updated": "2018-03-19T21:20:08.571Z"
  }
// See README.md for usage
exports.handler = (event, context, callback) => {
console.log(`${event.trace}: INFO JsonTransform ${JSON.stringify(event)}`)
try {
if (event.transformScript) {
let script = event.transformScript
delete event.transformScript
require('vm').runInNewContext(script, {event: event})
} else {
console.log(`${event.trace}: WARN JsonTransform missing field 'transformScript'}`)
}
callback(null, event)
} catch (err) {
console.log(`${event.trace}: ERROR JsonTransform ${JSON.stringify(err)}`)
callback(err)
}
}
@devilelephant
Copy link
Author

Note: we use a "trace" value throughout our system's design to track a process across tiers/logs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment