1
- import { custom_resources , aws_iam } from 'aws-cdk-lib' ;
1
+ import { custom_resources , aws_iam , Stack } from 'aws-cdk-lib' ;
2
2
import { Events } from '@aws-lambda-powertools/commons' ;
3
3
import { Construct } from 'constructs' ;
4
4
import { NodejsFunction , NodejsFunctionProps } from 'aws-cdk-lib/aws-lambda-nodejs' ;
5
- import { Tracing , Runtime } from 'aws-cdk-lib/aws-lambda' ;
5
+ import { Tracing , Runtime , LayerVersion } from 'aws-cdk-lib/aws-lambda' ;
6
6
7
7
interface ExampleFunctionProps {
8
8
readonly functionName : string
9
9
readonly tracingActive ?: boolean
10
+ readonly useLayer ?: boolean
10
11
readonly invocations ?: number
11
12
readonly fnProps ?: Partial < NodejsFunctionProps >
12
13
}
13
14
14
15
class ExampleFunction extends Construct {
15
-
16
16
public constructor ( scope : Construct , id : string , props : ExampleFunctionProps ) {
17
17
super ( scope , id ) ;
18
18
19
- const { functionName, tracingActive, invocations, fnProps } = Object . assign ( {
20
- tracingActive : false ,
21
- invocations : 2
22
- } , props ) ;
19
+ const { functionName, tracingActive, invocations, fnProps } = Object . assign (
20
+ {
21
+ tracingActive : false ,
22
+ invocations : 2 ,
23
+ } ,
24
+ props
25
+ ) ;
23
26
24
- const fn = new NodejsFunction ( this , functionName , {
27
+ const fnOptions = {
25
28
tracing : tracingActive ? Tracing . ACTIVE : Tracing . DISABLED ,
26
29
runtime : Runtime . NODEJS_16_X ,
27
- ...fnProps
28
- } ) ;
30
+ ...fnProps ,
31
+ } ;
32
+
33
+ if ( props . useLayer ) {
34
+ fnOptions . bundling = {
35
+ externalModules : [
36
+ '@aws-lambda-powertools/commons' ,
37
+ '@aws-lambda-powertools/logger' ,
38
+ '@aws-lambda-powertools/metrics' ,
39
+ '@aws-lambda-powertools/tracer' ,
40
+ ] ,
41
+ } ;
42
+ fnOptions . layers = [
43
+ LayerVersion . fromLayerVersionArn (
44
+ this ,
45
+ 'AWSLambdaPowertoolsTypeScript' ,
46
+ `arn:aws:lambda:${ Stack . of ( this ) . region } :094274105915:layer:AWSLambdaPowertoolsTypeScript:1`
47
+ ) ,
48
+ ] ;
49
+ }
50
+
51
+ const fn = new NodejsFunction ( this , functionName , fnOptions ) ;
29
52
30
53
for ( let i = 0 ; i < invocations ; i ++ ) {
31
54
new custom_resources . AwsCustomResource ( this , `Invoke-${ functionName } -${ i } ` , {
@@ -37,14 +60,12 @@ class ExampleFunction extends Construct {
37
60
FunctionName : fn . functionName ,
38
61
InvocationType : 'RequestResponse' ,
39
62
Payload : JSON . stringify ( Events . Custom . CustomEvent ) ,
40
- }
63
+ } ,
41
64
} ,
42
65
policy : custom_resources . AwsCustomResourcePolicy . fromStatements ( [
43
66
new aws_iam . PolicyStatement ( {
44
67
effect : aws_iam . Effect . ALLOW ,
45
- resources : [
46
- fn . functionArn ,
47
- ] ,
68
+ resources : [ fn . functionArn ] ,
48
69
actions : [ 'lambda:InvokeFunction' ] ,
49
70
} ) ,
50
71
] ) ,
@@ -53,6 +74,4 @@ class ExampleFunction extends Construct {
53
74
}
54
75
}
55
76
56
- export {
57
- ExampleFunction
58
- } ;
77
+ export { ExampleFunction } ;
0 commit comments