constructor()

in source/lib/awsnodejs-lambda-layer/layer.ts [46:95]


    constructor(scope: cdk.Construct, id: string, props: NodejsLayerVersionProps) {
        const compatibleRuntimes = props.compatibleRuntimes ?? [ lambda.Runtime.NODEJS_14_X ];

        for (const runtime of compatibleRuntimes) {
            if (runtime && runtime.family !== lambda.RuntimeFamily.NODEJS) {
                throw new Error('Only `Nodejs` runtimes are supported');
            }
        }

        const entry = path.resolve(props.entry);

        const baseFolderName = path.basename(entry);
        super(scope, id, {
            code: lambda.Code.fromAsset(entry, {
                bundling: {
                    image: lambda.Runtime.NODEJS_14_X.bundlingImage,
                    user: 'root',
                    local: { // attempts local bundling first, if it fails, then executes docker based build
                        tryBundle(outputDir: string) {
                            try {
                                spawnSync('echo "Trying local bundling of assets" && npm ci --only=prod');
                                const targetDirectory = `${outputDir}/nodejs/node_modules/${baseFolderName}`;
                                if (!fs.existsSync(targetDirectory)) {
                                    // recursively create the target path that include 'nodejs/node_modules'
                                    fs.mkdirSync(targetDirectory, {
                                        recursive: true
                                    });
                                }
                                NodejsLayerVersion.copyFilesSyncRecursively(entry, targetDirectory);
                            } catch(error){
                                console.error('Error with local bundling', error);
                                return false;
                            }
                            return true;
                        }
                    },
                    command: [
                        // executed only if local bundling fails. Docker becomes the sencondary deployment option
                        "bash", "-c", 'echo "local bundling failed and hence building with Docker image"', [
                            "npm ci --only=prod",
                            `mkdir -p /asset-output/nodejs/node_modules/${baseFolderName}`,
                            `cp -R /asset-input/* /asset-output/nodejs/node_modules/${baseFolderName}`
                        ].join(' && ')
                    ],
                }
            }),
            compatibleRuntimes,
            description: props.description
        } as lambda.LayerVersionProps);
    }