Transfer all specified resources from one stack to another in AWS CDK

In the process of creating two stacks, I aim to reference the resources from the first stack, such as Lambda, API Gateway, and DynamoDB, in the second stack without hard coding all the resources using Stack Props. Please note: I do not want to use Stack Props to manually input all the resources into the second stack. For example: File 1

export class StackOne extends cdk.Stack {
    constructor(scope: Construct, id: string, props: StackOneProps) {
    super(scope, id, { env: props.env });
    
    const lambda1 = new lambda.Function();
    const lambda2 = new lambda.Function();
    const api = new apigateway.RestApi()
    new apigateway.LambdaIntegration(
      lambda1
    );
    new apigateway.LambdaIntegration(
      lambda2
    );

    }
}

File 2

export class StackTwo extends cdk.Stack {
    constructor(scope: Construct, id: string, props: StackTwoProps) {
    super(scope, id, { env: props.env });
    
    const StackOne = //Acquire the StackOne Reference
    StackOne.Resourcs.forEach(rsourcs ==> {} )

    }
}

Answer №1

By setting the resources as public readonly properties, you can easily loop through the stack object's properties and identify those that are of type IResource (or any other type of interest).

export class StackExample extends cdk.Stack {
    public readonly resource1: Resource;
    public readonly resource2: Resource;
    // etc.

    constructor(scope: Construct, id: string, props: StackExampleProps) {
    super(scope, id, { env: props.env });
    
    this.resource1 = new Resource();
    this.resource2 = new Resource();
    // etc.
    }
}
export interface StackAnotherProps { 
    stackExample: Stack
}

export class StackAnother extends cdk.Stack {
    constructor(scope: Construct, id: string, props: StackAnotherProps) {
    super(scope, id, { env: props.env });
    
    const getResource = (r: any) => r instanceof IResource
        ? r
        : undefined;
    const keys = Object.keys(props.stackExample);
    const resources = keys
        .map(x => getResource(props.stackExample[x]))
        .filter(x => x !== undefined) as IResource);

    }
}

Answer №2

One potential way to access a Stack's synthesized children (the processed resources, not the original constructs you defined) is by utilizing escape hatch syntax: myStack.node.children.

However, it's important to note that this approach may not be advisable unless your specific use case is quite uncommon.

Typically, passing resource dependencies as props is considered the standard solution. If you find yourself in a situation where you need to transfer numerous resources between stacks, it could indicate that consolidating these resources within a single stack might be more efficient. You can refer to best practices for guidance on structuring your CDK applications accordingly.

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

Issue: Button ClickEvent is not triggered when the textArea is in onFocus mode

Is there a way to automatically activate a button ClickEvent when the textArea input is focused? Keep in mind that my textArea has some styles applied, causing it to expand when clicked. Here is an example: https://stackblitz.com/edit/angular-ivy-zy9sqj?f ...

Strategies for rapidly increasing user numbers in Amazon Cognito

Our team recently encountered an issue with hitting the request limit on Cognito due to trying to retrieve too many users at once. These users are grouped in game pools. Currently, our only method of obtaining users is through adminGetUser in parallel. Is ...

Converting an array of date strings to a single string in JavaScript

Here is the JSON format I received with dynamic data: {"range":["2018-07-23T16:03:26.861Z","2018-07-23T16:03:26.861Z"]} Now, I need to convert this into the following format: range(20180723,20180723) Below is my code snippet : var data:Date[] = {"rang ...

Commit to calculating the total sum of each element using AngularJS

Trying to implement a like counter using Facebook's GRAPH API. I have a list of object IDs and for each ID, I make an API call to retrieve the number of likes and calculate a total. The issue arises as the API call returns a promise, causing only one ...

The speed of npm installation on AWS EC2 has unexpectedly decreased

For years in my ElasticBeanstalk environment, it only took around 5 minutes for my Node.js app to deploy and switch from "Pending" to "OK" status in the EB Health tab. However, since May 14, the deployment time has increased to around 15 minutes without an ...

Is there a way to determine if a string is empty, even if it contains hard returns?

I am currently working on a function that checks if a string is empty or not, but it seems to be missing the detection of new lines. export const isStrEmpty = function(text: string): boolean { return !text || text.match(/^ *$/) !== null; }; I attempted ...

How can I display JSON values without revealing the parent in Angular 5 and Ionic 3?

I am trying to extract values from JSON without the parent keys. Here is the JSON structure I have: [ { "companies": [{ "id": 1, "name": "Prueba", "company_number": "23423423A", "latitude": 241241.12, "lo ...

What is the process for retrieving information from a retail outlet?

How can I retrieve data from the Vuex store using Vue.js? Below is my code: Vue.use(Vuex); export default new Vuex.Store({ modules: { data } }) data.js import axios from 'axios'; const state = { data: '' }; cons ...

Break down a data structure into a type that includes multiple options

Is it possible for Typescript to support type or interface "destructuring" (if that's the right term)? I am attempting to achieve something similar to the code snippet below: type SomeRandomType = { propertyOne: string; propertyTwo: number; ...

The 'jsx' property in tsconfig.json being overridden by Next.js and TypeScript

Is there a way to prevent NextJS from changing the 'jsx' property in my tsconfig.json file from 'react' to 'preserve' when running the development server? This is how my tsconfig.json file looks: "compilerOptions": { " ...

Swapping out the standard if/else logic for try/catch error

I'm facing a challenge in removing the then statements from this code snippet and replacing all catches with try/catch statements. I'm struggling to figure out how to handle the then statements. export class WelcomePageContribution implements IW ...

Challenges with Type Casting in TypeScript

Upon reviewing a specific piece of code, I noticed that it is not producing any compile time or run time errors even though it should: message: string // this variable is of type string -- Line 1 <br> abc: somedatatype // lets assume abc is of some ...

Implementing a feature in Typescript/React component that provides autocomplete functionality

Currently, I have developed a TypeScript and React component that has been published on NPM. My goal is to enable IntelliSense to autocomplete React props for this component. While I typically use JSDoc for plain React components, it does not seem to work ...

Can a custom structural directive be utilized under certain circumstances within Angular?

Presently, I am working with a unique custom structural directive that looks like this: <div *someDirective>. This specific directive displays a div only when certain conditions are met. However, I am faced with the challenge of implementing condit ...

Break down and extract elements using typedEvent in TypeScript

Within the external library, there is the following structure: export interface Event extends Log { args?: Result; } export interface TypedEvent<EventArgs extends Result> extends Event { args: EventArgs; } export type InstallationPreparedEven ...

The Angular2 view is failing to display updated data from a shared service

I've been struggling to show data from my shared service, but it's not displaying. Can someone please help me out? I've been stuck on this for the past few days. I've tried NgZone and ChangeDetectorRef, but they haven't worked for ...

The parameter 'unknown[]' cannot be assigned to the type 'OperatorFunction'

component.ts initialize() method explains The error message says 'Argument of type 'unknown[]' is not assignable to parameter of type 'OperatorFunction<unknown[], unknown>'. Type 'unknown[]' does not match the si ...

Incorporating a JavaScript npm module within a TypeScript webpack application

I am interested in incorporating the cesium-navigation JavaScript package into my project. The package can be installed via npm and node. However, my project utilizes webpack and TypeScript instead of plain JavaScript. Unfortunately, the package is not fou ...

Resolving search box setup problem in PrimeNG dataView

I am working on integrating p-dataView with Angular 5 but encountering an error Cannot read property 'split' of undefined at DataView.filter Despite checking the documentation, I have been unable to find a solution to this issue. It seems lik ...

Create an eye-catching hexagon shape in CSS/SCSS with rounded corners, a transparent backdrop, and a

I've been working on recreating a design using HTML, CSS/SCSS in Angular. The design can be viewed here: NFT Landing Page Design Here is a snippet of the code I have implemented so far (Typescript, SCSS, HTML): [Code here] [CSS styles here] [H ...