|
| 1 | +import { Construct } from 'constructs' |
| 2 | +import * as cdk from 'aws-cdk-lib' |
| 3 | +import * as lambda from 'aws-cdk-lib/aws-lambda' |
| 4 | +import * as cloudfront from 'aws-cdk-lib/aws-cloudfront' |
| 5 | +import * as logs from 'aws-cdk-lib/aws-logs' |
| 6 | +import * as iam from 'aws-cdk-lib/aws-iam' |
| 7 | +import path from 'node:path' |
| 8 | +import { buildLambda } from '../../build/edge' |
| 9 | +import { NextRedirects } from '../../types' |
| 10 | + |
| 11 | +interface ViewerRequestLambdaEdgeProps extends cdk.StackProps { |
| 12 | + buildOutputPath: string |
| 13 | + nodejs?: string |
| 14 | + redirects?: NextRedirects |
| 15 | +} |
| 16 | + |
| 17 | +const NodeJSEnvironmentMapping: Record<string, lambda.Runtime> = { |
| 18 | + '18': lambda.Runtime.NODEJS_18_X, |
| 19 | + '20': lambda.Runtime.NODEJS_20_X |
| 20 | +} |
| 21 | + |
| 22 | +export class ViewerRequestLambdaEdge extends Construct { |
| 23 | + public readonly lambdaEdge: cloudfront.experimental.EdgeFunction |
| 24 | + |
| 25 | + constructor(scope: Construct, id: string, props: ViewerRequestLambdaEdgeProps) { |
| 26 | + const { nodejs, buildOutputPath } = props |
| 27 | + super(scope, id) |
| 28 | + |
| 29 | + const nodeJSEnvironment = NodeJSEnvironmentMapping[nodejs ?? ''] ?? NodeJSEnvironmentMapping['20'] |
| 30 | + const name = 'viewerRequest' |
| 31 | + |
| 32 | + buildLambda(name, buildOutputPath, { |
| 33 | + define: { |
| 34 | + 'process.env.REDIRECTS': JSON.stringify(props.redirects ?? []) |
| 35 | + } |
| 36 | + }) |
| 37 | + |
| 38 | + const logGroup = new logs.LogGroup(this, 'ViewerRequestLambdaEdgeLogGroup', { |
| 39 | + logGroupName: `/aws/lambda/${id}-viewerRequest`, |
| 40 | + removalPolicy: cdk.RemovalPolicy.DESTROY, |
| 41 | + retention: logs.RetentionDays.ONE_DAY |
| 42 | + }) |
| 43 | + |
| 44 | + this.lambdaEdge = new cloudfront.experimental.EdgeFunction(this, 'ViewerRequestLambdaEdge', { |
| 45 | + runtime: nodeJSEnvironment, |
| 46 | + code: lambda.Code.fromAsset(path.join(buildOutputPath, 'server-functions', name)), |
| 47 | + handler: 'index.handler', |
| 48 | + logGroup |
| 49 | + }) |
| 50 | + |
| 51 | + logGroup.grantWrite(this.lambdaEdge) |
| 52 | + |
| 53 | + const policyStatement = new iam.PolicyStatement({ |
| 54 | + actions: ['logs:CreateLogStream', 'logs:PutLogEvents'], |
| 55 | + resources: [`${logGroup.logGroupArn}:*`] |
| 56 | + }) |
| 57 | + |
| 58 | + this.lambdaEdge.addToRolePolicy(policyStatement) |
| 59 | + } |
| 60 | +} |
0 commit comments