Transforming the velocity template within an API Gateway to be seamlessly integrated into Typescript using AWS CDK

Currently, I'm utilizing typescript in conjunction with AWS CDK to produce a cloudFormation template for an api gateway. The process involves using an Apache Velocity template to assist in converting my response data. However, as I go about creating the API gateway using typescript, I find myself facing a challenge - how do I pass the template directly from the code itself? Specifically, I have a requirement to pass my template within the responseTemplates property of the IntegrationOptions interface, which expects a string input. Unfortunately, thus far, I haven't been able to locate a straightforward method to convert the template into a string format.


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

Answer №1

If you're wondering how to create a long string in JavaScript without having to worry about escaping special characters, the solution lies in using javascript template literals.

By wrapping your string with backticks and utilizing String.raw, you can ensure that the content is passed as-is without any need for escaping or line continuation:

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

Answer №2

Creating a GraphQLApi in Java is quite straightforward:

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 simply provide the schema path and allow the CDK to handle loading and deploying the resource.

The TypeScript API seems to have a direct equivalence with APIs in other programming languages.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create an abstract method that will return the properties of the constructor

To establish an abstract class in typescript, we can name it Entity, which contains an abstract method called constructorProps() that returns the array of properties required to build the derived class. For instance, if Foo extends Entity and does not hav ...

When evaluating objects or arrays of objects to determine modifications

How can we detect changes in table data when users add input to cells? For example, if a user clicks on a cell and adds an input, the function should return TRUE to indicate that there are changes. If the user just clicks on the cell without making any ch ...

Subscribing to valueChanges in reactive forms to dynamically update checkbox options

My goal is to create a select dropdown with options for bmw, audi, and opel. The user can only select one option from the dropdown, but they should also have the ability to select the options that were not chosen using checkboxes. cars = [ { id: 1, na ...

Checking for unnecessary properties in Typescript with vue-i18n

Let's consider two different languages represented in JSON format: jp.json { "hello": "こんにちは" } ge.json { "hello": "hallo", "world": "welt" } Now, we are going to com ...

Typescript fails to properly identify the yield keyword within a generator function or generator body

Here is the code for my generator function: function* generatorFunction(input: number[]): IterableIterator<number> { input.forEach((num) => { yield num; }); An error occurred during linting: A 'yield' expression is only allowed ...

Having trouble exporting the APK file from Ionic

After running the ionic cordova build android --prod --release command, I encountered a compilation error with the following details. View the first part of the error Check out the second part of the error This is the output of my ionic info. View my i ...

Incorporating information into the output of an HTTP request with Angular 7

I have a list of asset IDs (assetIDs) and I need to fetch data using these IDs. Each HTTP request returns one or more datasets. My goal is to include the request ID in each dataset and then return the data. The process of fetching and returning the data i ...

In Typescript, issues arise when trying to assign types with inheritance in Generics - Type mismatch detected

As I work on creating a generic parent class to handle multiple children, I have encountered a challenge. My goal is to define an abstract function in the parent class that will take in a child object and return that same class. Here's my initial atte ...

Using Angular 2 with Typescript to call a JavaScript function

How can I correctly invoke a JavaScript function from a component in Angular 2 (TypeScript)? Below is the code for my component: import { ElementRef, AfterViewInit } from '@angular/core'; export class AppComponent implements AfterViewIni ...

"Exploring the power of index signatures and methods in Typescript

What might be the reason for code producing a ts(2411) error? class Greeter { [key: string]: string | number[]; greeting: string; constructor(message: string) { this.greeting = message; } greet(): string { return "Hel ...

Enrolling a new plugin into a software repository

I have 5 unique classes: ConfigManager ForestGenerator TreeCreator NodeModifier CustomPlugin My goal is to create an npm module using TypeScript that incorporates these classes. The main feature I want to implement is within the ConfigManager clas ...

Is it possible to create a nested object inside of an array?

Looking to accomplish the following: let listOne: any = ['item1', 'item2', 'item3']; let details: any; // Previously, I had a loop running and 'row' was the response outputting items // in the listOne array const ...

The function's overloading is not compatible with its implementation

Currently, I am puzzled by the lack of functionality in some code that I am reviewing. The structure resembles this: function getValidity(x: "v1"): boolean; function getValidity(x: "v2"): { a: number; b: number }; function getValidity(x: any) { if (x == ...

Saving many-to-many relationships with entities that are already saved in TypeORM

As a beginner in Typeorm, I have been working on a web page with Angular + Typeorm for the past few weeks. Despite my efforts to resolve this issue by myself and researching previously asked questions here on Stackoverflow, I have unfortunately been unable ...

In TypeScript Next.js 14 APP, object literals are limited to declaring existing properties

I encountered an error in my typescript next.js 14 APP. I need assistance resolving this issue, which states: Object literal may only specify known properties, and 'productPackages' does not exist in type '(Without<ProductCreateInput, Pr ...

Issue with updating initial state that is null in Redux Toolkit

Encountered an issue while using Redux Toolkit with Redux Persist. Unable to update the initial state of a user if it's null. The code consistently assigns null to the store regardless of passing parameters. import { createSlice, PayloadAction } from ...

TS2305 error: The module "/node_modules/rxjs/Rx" does not contain the 'Subscribable' member to export

I am currently working on an Angular 5 project and here is the package.json file: { "name": "ff-client", "version": "0.2.0", "license": "", ... } After installing npm and angular-cli, I ran npm install to get the required modules. However, when I ...

Issue with Framer-motion animation not triggering on exit

Here is a link to the code sandbox In this gif demonstration, it's evident that the notifications are not triggering the exit animation when removed from the DOM (usually after 6 seconds). Why is this happening? I've followed all the suggestion ...

Inserting items into an array entity

I am attempting to insert objects into an existing array only if a certain condition is met. Let me share the code snippet with you: RequestObj = [{ "parent1": { "ob1": value, "ob2": { "key1": value, "key2": va ...

When calling `mongoose.model()`, the second argument must either be a schema or a plain old JavaScript object (POJO)

Trying to launch my application but unsure which file is causing the issue. Can someone point me in the right direction? Here is a snippet of my app.module.ts file: import { Module } from '@nestjs/common'; import { ConfigModule } from '@nes ...