Home > Software design >  How can I bundle additional files with `NodejsFunction`?
How can I bundle additional files with `NodejsFunction`?

Time:01-18

I would like to upload an additional Html file to the code source like below. enter image description here

this is my code:

const mailerFunction = new aws_lambda_nodejs.NodejsFunction(this, 'ApiNotificationHandler', {
    runtime: lambda.Runtime.NODEJS_14_X,
    memorySize: 1024,
    timeout: cdk.Duration.seconds(3),
    handler: 'main',
    entry: path.join(__dirname, '../../src/mailer/index.ts'),
    environment: {
        SES_REGION,
        SES_EMAIL_FROM,
        SES_EMAIL_TO,
    }
});

I use a CDK 2.58.1 version. How could I upload additional html file to code source with cdk lambda?

CodePudding user response:

You can try to use command hooks. In Your example it would probably look like this (adjust the inputDir command):

const mailerFunction = new aws_lambda_nodejs.NodejsFunction(this, 'ApiNotificationHandler', {
    bundling: {
      commandHooks: {
        beforeBundling(inputDir: string, outputDir: string): string[] {
          return [`cp -r ${inputDir} ${outputDir}`] //adjust here
        },
        afterBundling(inputDir: string, outputDir: string): string[] {
          return []
        },
        beforeInstall(inputDir: string, outputDir: string): string[] {
          return []
        },
      },
    },
    runtime: lambda.Runtime.NODEJS_14_X,
    memorySize: 1024,
    timeout: cdk.Duration.seconds(3),
    handler: 'main',
    entry: path.join(__dirname, '../../src/mailer/index.ts'),
    environment: {
        SES_REGION,
        SES_EMAIL_FROM,
        SES_EMAIL_TO,
    }
});

CodePudding user response:

Copy the .html file by defining a commandHook in the bundling prop:

new NodejsFunction(this, "ApiNotificationHandler", {
  bundling: {
    commandHooks: {
      afterBundling: (inputDir: string, outputDir: string): string[] => [
        `cp ${inputDir}/path/from/root/to/email-template.html ${outputDir}`,
      ],
      beforeBundling: (inputDir: string, outputDir: string): string[] => [],
      beforeInstall: (inputDir: string, outputDir: string): string[] => [],
    },
  },
  // ...
});

The interface requires all three hooks to be defined. Choose one to implement the copying. Return an empty array as a no-op for the other two. inputDir will be the project root directory.

  • Related