Problem Statement
I'm in the process of writing an AWS API gateway and using Velocity Template Language (VTL) to transform my request into a structure that can be used by the backend. This has to be done on the API Gateway side since I have no control over the code that is calling the back, and the backend. The workflow is as follows:
-> legacy process sends request
-> API Gateway is invoked & transforms the request into a structure that is accepted by a lambda function
-> AWS lambda is invoked using transformed structure and returns a response
I have the template mostly figured out but there are a few niche cases surround special characters and I cannot find a solution that is universally able to resolve this.
Code
The transformation I have is as follows:
#set( $allParams = $input.params() )
#set( $InputBody = $util.escapeJavaScript($input.body) )
#set( $ParsedBody = $util.parseJson($input.body) )
#set( $text = $util.escapeJavaScript($ParsedBody.text) )
#set( $textString = $text.toString() )
#set( $text_language = $ParsedBody.language )
#set( $body = {
"text": $textString,
"categories": ["ALL"],
"text_language": $text_language,
"str_language_variants": ["en"]
})
#set($bodyString = $body.toString())
{
"body": "{\n \"text\": \"$textString\",\n \"text_language\": \"$text_language\",\n \"str_language_variants\": [\"en\"], \n}",
}
}
Test Cases
- The first test case has an inner
\"which does not parse correctly
{
"text": "besponsa sounds like \"famosa\" in spanish",
"mode": "fb",
"language": "en"
}
The error that I'm getting is:
Missing key arguments in the payloads ('text')
- The second test case has a newline character in the text
\nwhich with the above code is fine
{
"text": "<i>Anxiety depression asthma Omicron</i> ad \n asthma anxiety, viagra, sildenafil, enzyme , mrtx1719",
"mode": "all",
"language": "en"
}
Attempted Solution(s)
The only solution that has shown promise for the first case is if add a replace() method into the $textString to be as follows:
"body": "{\n \"text\": \"$textString\"... -> "body": "{\n \"text\": \"$textString.replace("\", "\\\"),\"
But this fails when I run test case 2.
Question
Is there anyway of having the VTL parse for both special character types while maintaining as much of the code above?