|
| 1 | +import { Function, FunctionProps, Runtime } from 'aws-cdk-lib/aws-lambda'; |
| 2 | +import { Duration, Stack } from 'aws-cdk-lib'; |
| 3 | +import { Construct } from 'constructs'; |
| 4 | +import { functionDefaults } from './defaults'; |
| 5 | +import { functionLayer } from '../layers'; |
| 6 | +import { packagePhpCode } from '../package'; |
| 7 | + |
| 8 | +export type PhpFunctionProps = Partial<FunctionProps> & { |
| 9 | + phpVersion?: '8.0' | '8.1' | '8.2'; |
| 10 | + handler: string; |
| 11 | +}; |
| 12 | + |
| 13 | +export class PhpFunction extends Function { |
| 14 | + constructor(scope: Construct, id: string, props: PhpFunctionProps) { |
| 15 | + const defaults = { |
| 16 | + runtime: Runtime.PROVIDED_AL2, |
| 17 | + code: props.code ?? packagePhpCode(), |
| 18 | + timeout: Duration.seconds(6), |
| 19 | + memorySize: functionDefaults.memorySize, |
| 20 | + }; |
| 21 | + |
| 22 | + // Put the layers aside for now, we set them after `super()` |
| 23 | + const layers = props.layers ?? []; |
| 24 | + |
| 25 | + super(scope, id, { |
| 26 | + ...defaults, |
| 27 | + // Provided props override defaults |
| 28 | + ...props, |
| 29 | + // But we force the layers to an empty array because we define them below |
| 30 | + layers: [], |
| 31 | + }); |
| 32 | + |
| 33 | + // Add layer afterwards so that we can use `this` to resolve the region |
| 34 | + const region = Stack.of(this).region; |
| 35 | + if (region.startsWith('${')) { |
| 36 | + throw new Error( |
| 37 | + 'Cannot detect the AWS region. Bref needs the AWS region to know which AWS layer to use. In order to use Bref layers, you must explicitly set the region for the stack. See https://gist.github.com/mnapoli/7c7eab49444637426ce66a24df715a63' |
| 38 | + ); |
| 39 | + } |
| 40 | + const phpVersion = props.phpVersion ?? functionDefaults.phpVersion; |
| 41 | + this.addLayers( |
| 42 | + // Add the function layer first so that other layers can override it |
| 43 | + functionLayer(scope, region, phpVersion, functionDefaults.platform), |
| 44 | + ...layers |
| 45 | + ); |
| 46 | + } |
| 47 | +} |
0 commit comments