Abhinandan Mittal
Abhinandan Mittal

Reputation: 15

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
    ] 
}

Upvotes: 1

Views: 1121

Answers (2)

alessiosavi
alessiosavi

Reputation: 3055

In java, is very simple:

private GraphQLApi CreateGraphQLApi(String API_NAME) {
    return GraphQLApi.Builder.create(this, API_NAME + "_AppSyncApi")
            .name(API_NAME.concat("_AppSyncApi"))
            .schemaDefinitionFile(Constants.SCHEMA_PATH)
            .build();
}

You can pass the schema path and let the cdk load and deploy the resource.

I think that the typescript API have a 1 to 1 match with other languages

Upvotes: 0

TheClassic
TheClassic

Reputation: 1044

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
    ] 
}`

Upvotes: 3

Related Questions