Lambda events where "method" is the only changing property
Description: I'm new to SAM and I'm loving the fact that a small template file encloses a lot of functionality, hence, I would like to suggest a minor template syntax change that would make writing HTTP APIs faster. In particular I'm working with an Http Api and I'm finding it a bit tedious to write event sources of type HttpApi (though this suggestion would be valid for normal APIs as well) for lambda functions where the only changing property is the method.
E.g. Let's assume that I have predefined in the same template an HttpApi resource that does not specify an OpenApi model, now I want to define a lambda function that needs to be called for a route "/path/to/route" with a JWT authorizer called "MyCognitoAuthorizer" defined in the HttpApi and for methods GET, POST, PUT and DELETE. With the current syntax the template code for this function would look like:
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: code/uri
Events:
getEvent:
Type: HttpApi
Properties:
ApiId: !Ref MySAMApi
Method: GET
Path: /path/to/route
Auth:
Authorizer: MyCognitoAuthorizer
postEvent:
Type: HttpApi
Properties:
ApiId: !Ref MySAMApi
Method: POST
Path: /path/to/route
Auth:
Authorizer: MyCognitoAuthorizer
putEvent:
Type: HttpApi
Properties:
ApiId: !Ref MySAMApi
Method: PUT
Path: /path/to/route
Auth:
Authorizer: MyCognitoAuthorizer
deleteEvent:
Type: HttpApi
Properties:
ApiId: !Ref MySAMApi
Method: DELETE
Path: /path/to/route
Auth:
Authorizer: MyCognitoAuthorizer
As you can see, this is very long and repetitive and breaks the DRY principle.
Unfortunately this problem cannot be solved with globals because events property for functions is not supported in globals. In addition, I know I could simply write just ANY as the method, but I don't want all methods. Also, I know that I could still use ANY and check for unwanted methods in my lambda handler, but this can mess with CORS and nobody wants to mess with CORS.
Finally, my suggested feature is to add a property called "methods" in the HttpApi event (but could be done for normal Apis as well) such that the following code would be equivalent to the above code, but much shorter:
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: code/uri
Events:
MyRESTEvent:
Type: HttpApi
Properties:
ApiId: !Ref MySAMApi
Path: /path/to/route
Auth:
Authorizer: MyCognitoAuthorizer
Methods:
- GET
- POST
- PUT
- DELETE
Thanks a lot @ChristianMarchetta for the suggestion, I will label this for internal review. But my concern is about the method-specific configurations, like RequestParameters for example.
Also, it is a common practice that different HTTP methods are handled by different lambda functions as well.
What do you think about this?