Serverless Framework: AWS Lambdas with scheduled events and parameters

To configure an AWS Lambda to get triggered by a CloudWatch event, you can use the ‘schedule’ event in your config:

functions:
  your-function-name:
    handler: your.Handler
    timeout: 30
    events:
      - schedule:
          rate: rate(12 hours)
          input:
            puzzles : "2"
            targetGivens : "20"

You can also pass parameters from the CloudWatch event when your Lambda is invoked by listing them under ‘input’ (this is optional if your Lambda doesn’t take any parameters).

There schedule config is covered in the docs here, but there doesn’t seem to be any official docs for input, but I found this in a reply to a question here.

Serverless Framework API Gateway CORS config

If you deploy a Serverless Framework Java Lambda to AWS and attempt to call it locally while developing your frontend, you’ll run into a CORS error like this:

Access to XMLHttpRequest at 'https://abc.execute-api.us-west-1.amazonaws.com/some/api' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Posts suggest to set a cors option under the event in your serverless.yaml like this:

events:
  - http:
    path: handlerPath
    method: post
    cors:
      origin: '*'

… but in current versions of Serverless this results in an error like this:

Serverless:   at 'functions['example'].events[0].httpApi': unrecognized property 'cors'

From this post, it mentions the cors options has moved up into the provider section:

provider:
  name: aws
  runtime: java8
  lambdaHashingVersion: 20201221
  httpApi:
    cors: true

This is in the docs here.

This works great!

What does this option do? It looks like it sets these options in API Gateway:

‘serverless invoke local’ with Java Lambdas

If you create a Java Lambda with the provided template, you’re probably returning a response using the provided ApiGatewayResponseClass. If you run your Lambda locally with ‘serverless invoke local –function functioname’, you’ll see a response like this:

Serverless: Invoke invoke:local
Serverless: In order to get human-readable output, please implement "toString()" method of your "ApiGatewayResponse" object.

com.serverless.ApiGatewayResponse@3bd3d05e

Any other logger output will appear in your console, but in order to see the actual content of your ApiGatewayResponse, add a toString() method as the message suggests.

You include any of the properties in ApiGatewayResponse, but if you’re just interested in the JSON payload in the body of the response, then just adding this will return the body:

public String toString(){
    return this.body;
}