0

I am new to AWS CDK and TypeScript. Have a general question related to typescript in context with AWS CDK. I tried to find a similar example or question being asked in stackoverflow but could not find. In the code snippet below, what does this refer to in terms of context?

// An sqs queue for unsuccessful invocations of a lambda function
import * as sqs from 'aws-cdk-lib/aws-sqs';

const deadLetterQueue = new sqs.Queue(this, 'DeadLetterQueue');

const myFn = new lambda.Function(this, 'Fn', {
  runtime: lambda.Runtime.NODEJS_14_X,
  handler: 'index.handler',
  code: lambda.Code.fromInline('// your code'),
  // sqs queue for unsuccessful invocations
  onFailure: new destinations.SqsDestination(deadLetterQueue),
});

https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_sqs.Queue.html
user391
  • 105
  • 1
  • 12
  • What environment? In the browser, it's `window`, and in node, it's [this](https://stackoverflow.com/questions/43627622/what-is-the-global-object-in-nodejs). – kelsny Nov 07 '22 at 20:31
  • 1
    `this` in that code is your stack. It's required for all components to have a reference to their construct/stack. `this` in modern typescript in general is mostly the current instance of the class your code is in. E.g. in `class MyStack extends cdk.Stack { ... this ... }` it's probably the current instance of `MyStack`. `this` in Typescript/JS is a little tricky if you use `function`s https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this though. – zapl Nov 07 '22 at 20:54

1 Answers1

1

The sample code is incomplete. This type of code is found in the context of a Construct. A more plausible version would be something like this:

// An sqs queue for unsuccessful invocations of a lambda function

import * as sqs from 'aws-cdk-lib/aws-sqs';

export class MyConstruct extends Construct {
  
  constructor(scope: Construct, id: string) {
    super(scope, id);
    const deadLetterQueue = new sqs.Queue(this, 'DeadLetterQueue');
    
    const myFn = new lambda.Function(this, 'Fn', {
      runtime: lambda.Runtime.NODEJS_14_X,
      handler: 'index.handler',
      code: lambda.Code.fromInline('// your code'),
      // sqs queue for unsuccessful invocations
      onFailure: new destinations.SqsDestination(deadLetterQueue),
    });
  }
}

// https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_sqs.Queue.html

this then references the construct. This pattern is seen all CDK code. MyConstruct will probably be referenced inside a stack:

new MyConstruct(this, 'my-construct');

Here, 'this' would reference the Stack it's in.