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

Obtain a union type using the `keyof typeof` syntax

Is there a way to retrieve the union or enum type from a typeof type in TypeScript? For instance: const myConfs: { [k: string]: (myArg: { name: string }) => string } = { 'Hello': ({ name }) => `World from ${name}`, 'Goodbye': ...

Verify whether an object possesses all the attributes of a class in TypeScript

Within my typescript code, I have a class called abc: export class ABC{ public a : any; public b : any; public c? : any; public d? : any; } In one of my functions, I receive an input which is represented as data:any. My goal is to verify i ...

Exploring dependency injection in Angular 1 using a blend of JavaScript and TypeScript

I'm currently working on integrating TypeScript into an existing Angular 1.5 application. Despite successfully using Angular services and third-party services, I am facing difficulties in injecting custom services that are written in vanilla JavaScrip ...

The argument representing 'typeof Store' cannot be assigned to the parameter representing 'Store<AppState>'

I'm encountering an issue while trying to expand a service in Angular that utilizes ngrx. The error message I'm receiving is as follows: Argument of type 'typeof Store' is not assignable to parameter of type 'Store<AppState>& ...

How can I redirect a page using an axios interceptor in Next.js?

Is there a way to redirect the page in an axios interceptor when dealing with server-side rendering limitations? Unfortunately, I am unable to access the server side context in the axios interceptor. I have tried using next/router but it only works on the ...

What is the best way to fetch all Firebase database IDs using Angular?

Is there a way to fetch all data from Firebase database along with their respective IDs? Currently, I have two functions - getAll() and get(input) that retrieve specific products based on the given ID. However, my current implementation only returns obje ...

An error occurred with the datepicker: Unable to connect to 'bsValue' as it is not recognized as a property of 'input'

Despite importing DatepickerModule.forRoot() in my Angular unit test, I am encountering the following error: Error: Template parse errors: Can't bind to 'bsConfig' since it isn't a known property of 'input'. (" ...

Translating SQL to Sequelize Syntax

I have an SQL query that I need to rewrite as a sequelize.js query in node.js. SELECT historyTable1.* FROM table1 historyTable1 WHERE NOT EXISTS ( SELECT * FROM table1 historyTable2 WHERE historyTable2.id=historyTable1.id AND historyTable2.da ...

Tips for resolving the ExtPay TypeError when using Typscript and Webpack Bundle

I am currently trying to install ExtPay, a payment library for Chrome Extension, from the following link: https://github.com/Glench/ExtPay. I followed the instructions up until step 3 which involved adding ExtPay to background.js. However, I encountered an ...

Struggling with transitioning from TypeScript to React when implementing react-data-grid 7.0.0

I'm trying to add drag and drop functionality to my React project using react-data-grid, but I keep encountering a "TypeError: Object(...) is not a function" error. I have a TypeScript version of the file in the sandbox as a reference, but when I try ...

Setting Angular FormControl value to null within a service

My Angular form is reactive and collects mobile numbers along with other details. Here is the code snippet: component.html <form [formGroup]="contactDetailsForm"> <ngx-intl-tel-input [cssClass]="'ngxIntlInputBorder'&quo ...

Error: The property you are trying to set is undefined and cannot

When I attempt to set a property 'error' that is undefined, I receive a TypeError. The problematic line of code looks like this: this.error = error.code; This issue arises in an Angular Reactive Form while making a call to a web service. Below i ...

Issue in VueJs where mutations do not properly save new objects to the state

I am facing an issue with updating my vuex store after modifying my user credentials in a component. Below is the code snippet for reference: mutations: { updateUserState: function(state, user) { state.user = user; }, } actions: { updat ...

React.js: You cannot call this expression. The type 'never' does not have any call signatures

Could someone help me troubleshoot the error I'm encountering with useStyles? It seems to be related to Typescript. Here's the line causing the issue: const classes = useStyles(); import React from "react"; import { makeStyles } from & ...

Getting Typescript Compiler to Recognize Global Types: Tips and Strategies

In the top level of my project, I have defined some global interfaces as shown below: globaltypes.ts declare global { my_interface { name:string } } However, when attempting to compile with ts-node, the compiler fails and displays the er ...

Getter and Setter Implementation in Typescript without Using Classes

Check out these various SO questions discussing Typescript getters/setters: from 2015, Jan 2018, Sept 2018, and more. Now, the question arises - what is the best approach to define Typescript types for getters/setters in a plain JavaScript object without ...

Unraveling the mysteries of webpack configuration

import * as webpack from 'webpack'; ... transforms.webpackConfiguration = (config: webpack.Configuration) => { patchWebpackConfig(config, options); While reviewing code within an Angular project, I came across the snippet above. One part ...

Best practices and distinctions when it comes to typing in TypeScript functions

Do the typings below differ in any way, or are they essentially the same with personal preference? interface ThingA{ myFunc(): number; } interface ThingB{ myFunc: () => number; } ...

"An error has occurred stating that the header is not defined in

It is a coding issue related to payment methods. The headers type is undefined in this scenario, and as a newcomer to typescript, pinpointing the exact error has been challenging. An error message is indicating an issue with the headers in the if conditio ...

Typescript: Displaying two values as input (one being disregarded)

Is there a way to display both the name and id values in an input box that is set to readonly? <input readonly type="text" [value]="car.name"> I need to also show the car id. Any suggestions on how to achieve this? ...