简体   繁体   English

Lambda 可以从直接调用和 SNS 消息中获取 arguments

[英]Lambda that can get arguments from both direct invocation and SNS message

Is it possible to construct a Lambda handler such that it will be able to get its arguments from either SNS, or via direct invocation?是否可以构造一个 Lambda 处理程序,以便能够从 SNS通过直接调用获取其 arguments?
In other words, the same Lambda can be invoked either explicitly or via subscription to SNS topic.换句话说,可以显式或通过订阅 SNS 主题调用相同的 Lambda。

Purpose is to have a Lambda that is usually triggered via SNS 90% of the time, but also allow for manual invocation via Console or web API.目的是让 Lambda 通常在 90% 的时间内通过 SNS 触发,但也允许通过控制台或 web API 手动调用。

It looks like this may be possible via something like看起来这可以通过类似的东西实现

def lambda_handler(event, context):
   args = parse_sns_event(event) if 'Records' in event else event

Assuming that 'Records' is the top-level key in the Lambda SNS event , and that 'Records' is not the name of one of the expected arguments.假设“记录”是Lambda SNS 事件中的顶级键,并且“记录”不是预期的 arguments 之一的名称。

Is there a better way to do this?有一个更好的方法吗? (Short of having two Lambdas - one main worker plus another to receive the SNS message and invoke the other) (缺少两个 Lambda - 一个主要工作人员加上另一个接收 SNS 消息并调用另一个)

Your idea for checking for 'Records' is a good one. 您检查'Records'想法很不错。 When you invoke manually you can pass whatever payload you like so as long as it doesn't include 'Records' then you've got your decision point. 手动调用时,只要不包含'Records'就可以传递所需的任何有效负载,那么您就有了决策要点。

Example: 例:

def handler(event, context):
    if 'Records' in event:
        # Handle SNS trigger
    else:
        # Handle manual trigger

You can pass a payload that you define via the AWS CLI: 您可以传递通过AWS CLI定义的有效负载:

aws lambda invoke --function-name your-lambda-function --payload '{"Manual":"yes"}'

What I have done in the past is created a service class that has all the logic我过去所做的是创建一个具有所有逻辑的服务 class

ie LoginService takes in all the params it needs onlyLoginService接受它只需要的所有参数

Then created 2 functions and I thought of them as controller endpoints Those endpoints all they do is get the params validate them then send them to the service然后创建了 2 个函数,我认为它们是 controller 端点这些端点他们所做的就是获取参数验证它们然后将它们发送到服务

If called the wrong way the validation would tell the caller如果以错误的方式调用,验证会告诉调用者

I hope this helps.我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM