This repository was archived by the owner on Aug 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 345
/
Copy pathhitcounter.go
64 lines (52 loc) · 1.79 KB
/
hitcounter.go
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
64
package hitcounter
import (
"github.com/aws/aws-cdk-go/awscdk/v2"
"github.com/aws/aws-cdk-go/awscdk/v2/awsdynamodb"
"github.com/aws/aws-cdk-go/awscdk/v2/awslambda"
"github.com/aws/constructs-go/constructs/v10"
"github.com/aws/jsii-runtime-go"
)
type HitCounterProps struct {
Downstream awslambda.IFunction
ReadCapacity float64
}
type hitCounter struct {
constructs.Construct
handler awslambda.IFunction
table awsdynamodb.Table
}
type HitCounter interface {
constructs.Construct
Handler() awslambda.IFunction
Table() awsdynamodb.Table
}
func NewHitCounter(scope constructs.Construct, id string, props *HitCounterProps) HitCounter {
if props.ReadCapacity < 5 || props.ReadCapacity > 20 {
panic("ReadCapacity must be between 5 and 20")
}
this := constructs.NewConstruct(scope, &id)
table := awsdynamodb.NewTable(this, jsii.String("Hits"), &awsdynamodb.TableProps{
PartitionKey: &awsdynamodb.Attribute{Name: jsii.String("path"), Type: awsdynamodb.AttributeType_STRING},
RemovalPolicy: awscdk.RemovalPolicy_DESTROY,
Encryption: awsdynamodb.TableEncryption_AWS_MANAGED,
ReadCapacity: jsii.Number(props.ReadCapacity),
})
handler := awslambda.NewFunction(this, jsii.String("HitCounterHandler"), &awslambda.FunctionProps{
Runtime: awslambda.Runtime_NODEJS_16_X(),
Handler: jsii.String("hitcounter.handler"),
Code: awslambda.Code_FromAsset(jsii.String("lambda"), nil),
Environment: &map[string]*string{
"DOWNSTREAM_FUNCTION_NAME": (*props).Downstream.FunctionName(),
"HITS_TABLE_NAME": table.TableName(),
},
})
table.GrantReadWriteData(handler)
props.Downstream.GrantInvoke(handler)
return &hitCounter{this, handler, table}
}
func (h *hitCounter) Handler() awslambda.IFunction {
return h.handler
}
func (h *hitCounter) Table() awsdynamodb.Table {
return h.table
}