-
Notifications
You must be signed in to change notification settings - Fork 6
/
scheduled-lambda.ts
63 lines (60 loc) · 2.21 KB
/
scheduled-lambda.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import { Rule } from "aws-cdk-lib/aws-events";
import type { RuleTargetInput, Schedule } from "aws-cdk-lib/aws-events";
import { LambdaFunction } from "aws-cdk-lib/aws-events-targets";
import type { GuLambdaErrorPercentageMonitoringProps, NoMonitoring } from "../constructs/cloudwatch";
import type { GuStack } from "../constructs/core";
import { GuLambdaFunction } from "../constructs/lambda";
import type { GuFunctionProps } from "../constructs/lambda";
export interface GuScheduledLambdaProps extends Omit<GuFunctionProps, "errorPercentageMonitoring"> {
/**
* Schedule(s) for the lambda task.
*/
rules: Array<{
/**
* E.g.:
*
* - `Schedule.expression("cron(0 8 ? * MON-FRI *)")`
* - `Schedule.rate(Duration.minutes(5))`
*/
schedule: Schedule;
/**
* Optional description.
*/
description?: string;
/**
* Optional input
*/
input?: RuleTargetInput;
}>;
/**
* Monitoring configuration for the lambda.
*
* Opting-out via the `NoMonitoring` type is supported but discouraged.
*/
monitoringConfiguration: NoMonitoring | GuLambdaErrorPercentageMonitoringProps;
}
/**
* Pattern which creates all of the resources needed to invoke a lambda function on a schedule.
*
* For all configuration options, see [[`GuScheduledLambdaProps`]].
*/
export class GuScheduledLambda extends GuLambdaFunction {
constructor(scope: GuStack, id: string, props: GuScheduledLambdaProps) {
const lambdaProps: GuFunctionProps = {
...props,
errorPercentageMonitoring: props.monitoringConfiguration.noMonitoring ? undefined : props.monitoringConfiguration,
};
super(scope, id, lambdaProps);
props.rules.forEach((rule, index) => {
// If we have an alias, use this to ensure that all invocations are handled by a published Lambda version.
// Otherwise, use the latest unpublished version ($LATEST)
const resourceToInvoke = this.alias ?? this;
new Rule(this, `${id}-${rule.schedule.expressionString}-${index}`, {
schedule: rule.schedule,
targets: [new LambdaFunction(resourceToInvoke, { event: rule.input })],
...(rule.description && { description: rule.description }),
enabled: true,
});
});
}
}