Search code examples
typescriptamazon-web-servicesaws-api-gatewayaws-cdkvelocity-template-language

Converting velocity template in api gateway to be passed in typescript with AWS CDK


I'm using typescript with AWS CDK to generate a cloudFormation template for api gateway. I've a Apache Velocity template that helps me convert my response. While I'm creating the API gateway using typescript. How can I pass the template from code itself. I need to pass my template in responseTemplates in IntegrationOptions interface which expects a string. I've not been able to find any reasonable way to convert it to string.

{
    "sellableQuantity": $inputRoot.quantity),
    "reservedQuantity": $inputRoot.reservedQuantity)
    "marketplaceInventories": [
        #foreach( $marketplaceInventory in $inputRoot.marketplaceInventories) )
            {
                "sellableQuantity": $marketplaceInventory.sellableQuantity,
                "marketplaceAttributes": {
                    #set( $marketplaceAttributes = $marketplaceInventory.marketplaceAttributes )
                    "marketplaceName": "$marketplaceAttributes.marketplaceName",
                    "channelName": "$marketplaceAttributes.channelName"
                }
            }
            #if( $foreach.hasNext ) , #end
        #end
    ] 
}

Solution

  • Your question really is "How do I define a long string without worrying about escaping special characters in javascript?"

    I think a javascript template literal is the best choice as it allows you to not worry about escaping or line continuation. Using backticks around your string and String.raw you can ensure that what you define will be passed verbatim:

    let myVelocityTemplate = String.raw`{
        "sellableQuantity": $inputRoot.quantity),
        "reservedQuantity": $inputRoot.reservedQuantity)
        "marketplaceInventories": [
            #foreach( $marketplaceInventory in $inputRoot.marketplaceInventories) )
                {
                    "sellableQuantity": $marketplaceInventory.sellableQuantity,
                    "marketplaceAttributes": {
                        #set( $marketplaceAttributes = $marketplaceInventory.marketplaceAttributes )
                        "marketplaceName": "$marketplaceAttributes.marketplaceName",
                        "channelName": "$marketplaceAttributes.channelName"
                    }
                }
                #if( $foreach.hasNext ) , #end
            #end
        ] 
    }`