首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何捕获无服务器lambda数据源中的AWS事件

如何捕获无服务器lambda数据源中的AWS事件
EN

Stack Overflow用户
提问于 2020-02-03 20:11:56
回答 3查看 447关注 0票数 0

我正在为一个AppSync API使用一个无服务器的lambda数据源。

我在lambda函数中尝试了以下代码

代码语言:javascript
复制
package main

import (
    "context"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"
    "log"
)

func main() {
    lambda.Start(Handler)
}
// Handler is your serverless lambda function
func Handler(ctx context.Context, event events.AppSyncResolverTemplate) error {
    log.Println(ctx)
    log.Println(event)
    return nil
}

当我对API进行查询时,上下文被正确记录,但事件被记录为{ []}

我尝试将lambda代码更改为使用空接口的事件

代码语言:javascript
复制
package main

import (
    "context"
    "github.com/aws/aws-lambda-go/lambda"
    "log"
)


func main() {
    lambda.Start(Handler)
}

// Handler is your serverless lambda function
func Handler(ctx context.Context, event interface{}) error {
    log.Println(ctx)
    log.Println(event)
    return nil
}

现在查询API,我可以看到logs map[field:getPerson arguments:map[personId:1]]中有一个映射。

我的问题是,在处理程序签名中应该使用什么有效类型来捕获AppSync事件?

EN

回答 3

Stack Overflow用户

发布于 2020-11-22 22:03:08

如果您使用的是2020年8月推出的新的直接Lambda解析器(https://aws.amazon.com/blogs/mobile/appsync-direct-lambda/),那么直到今天才能在当前Golang AWS SDK中的Appsync上找到事件类型。

它们只有AppSyncResolverTemplate、AppSyncIAMIdentity和AppSyncCognitoIdentity结构(https://github.com/aws/aws-lambda-go/blob/v1.16.0/events/appsync.go),所以如果你打算使用直接的lambda解析器,你必须自己解码传入的请求。

到目前为止他们还没有这么做的原因是因为到目前为止,你可以使用模板解析器(在AppSync中)来设计你自己的模式,但是现在Direct Lambda特性已经失效了,我想他们必须为此创建一个新的AppSync事件类型。

在此之前,我将与你分享我写的代码,为了这个目的一块一块地提取整个事件,希望能为下一个处于我这种境地的人节省一些时间。

*您会注意到,这里没有错误处理,只有解码来自AppSync的AWS事件所需的代码;-)

代码语言:javascript
复制
package main

import (
    "fmt"
    "context"
    "github.com/aws/aws-lambda-go/lambda"
    "github.com/aws/aws-lambda-go/lambdacontext"
    "log"
    "encoding/json"
    "bytes"
)

type Event struct {
    Arguments               map[string]string `json:"arguments"`
    Identity                string `json:"identity"`
    Info struct {
        FieldName           string `json:"fieldName"`
        ParentTypeName      string `json:"parentTypeName"`
        SelectionSetGraphQL string `json:"selectionSetGraphQL"`
        SelectionSetList    []string `json:"selectionSetList"`
        Variables           map[string]string `json:"variables"`
    }
    Prev                    string `json:"prev"`
    Request struct { 
        Headers struct {
            Accept                      string `json:"accept"`
            AcceptEncoding              string `json:"accept-encoding"`
            AcceptLanguage              string `json:"accept-language"`
            CloudfrontForwardedProto    string `json:"cloudfront-forwarded-proto"`
            CloudfrontIsDesktopViewer   string `json:"cloudfront-is-desktop-viewer"`
            CloudfrontIsMobileViewer    string `json:"cloudfront-is-mobile-viewer"`
            CloudfrontIsSmarttvViewer   string `json:"cloudfront-is-smarttv-viewer"`
            CloudfrontViewerCountry     string `json:"cloudfront-viewer-country"`
            CloudfrontIsTabletViewer    string `json:"cloudfront-is-tablet-viewer"`
            ContentLength               string `json:"content-length"`
            ContentType                 string `json:"content-type"`
            Host                        string `json:"host"`
            Hrigin                      string `json:"origin"`
            Referer                     string `json:"Referer"`
            SecFetchDest                string `json:"sec-fetch-dest"`
            SecFetchMode                string `json:"sec-fetch-mode"`
            SecFetchSite                string `json:"sec-fetch-site"`
            UserAgent                   string `json:"user-agent"`
            Via                         string `json:"via"`
            XAmzCfID                    string `json:"x-amz-cf-id"`
            XAmzUserAgent               string `json:"x-amz-user-agent"`
            XAmznTraceID                string `json:"x-amzn-trace-id"`
            XApiKey                     string `json:"x-api-key"`
            XForwardedFor               string `json:"x-forwarded-for"`
            XForwardedPort              string `json:"x-forwarded-port"`
            XForwardedProto             string `json:"x-forwarded-proto"`
        }
    }
    Source              string `json:"source"`
    Stash               map[string]string `json:"stash"`
}


func main() {
    lambda.Start(HandleLambdaEvent)
}

func HandleLambdaEvent(ctx context.Context, event interface{}) error {

    fmt.Printf("---------------{LAMBDA ctx Start}---------------\n")
    // Event context
    lc, _ := lambdacontext.FromContext(ctx)
    //fmt.Println("Context:",ctx)
    fmt.Println("AwsRequestID:",lc.AwsRequestID)
    fmt.Println("Identity:",lc.Identity)
    fmt.Println("InvokedFunctionArn:",lc.InvokedFunctionArn)
    fmt.Println("ClientContext:",lc.ClientContext)
    fmt.Println("ClientContext.Client:",lc.ClientContext.Client)
    fmt.Println("CognitoIdentityID:",lc.Identity.CognitoIdentityID)
    fmt.Println("CognitoIdentityPoolID:",lc.Identity.CognitoIdentityPoolID)
    deadline, _ := ctx.Deadline()
    fmt.Println("ContextDeadline:",deadline)


    fmt.Printf("---------------{LAMBDA AWS Event Start}---------------\n")
    log.Println(event)


    fmt.Printf("---------------{Marshal Event Start}---------------\n")
    //eventJsonm, _ := json.Marshal(event)
    eventJsonm, _ := json.MarshalIndent(event, "", "    ")
    log.Printf("EVENT Marsal: %s", eventJsonm)
    

    fmt.Printf("---------------{Decode Start}---------------\n")
    var Event Event
    r := bytes.NewReader([]byte(eventJsonm))
    json.NewDecoder(r).Decode(&Event)
    fmt.Println("Arguments:",Event.Arguments)
    fmt.Println("Identity:",Event.Identity)
    fmt.Println("Info.FieldName:",Event.Info.FieldName)
    fmt.Println("Info.ParentTypeName:",Event.Info.ParentTypeName)
    fmt.Println("Info.SelectionSetGraphQL:",Event.Info.SelectionSetGraphQL)
    fmt.Println("Info.SelectionSetList:",Event.Info.SelectionSetList)
    fmt.Println("Info.Variables:",Event.Info.Variables)
    fmt.Println("Prev:",Event.Prev)
    // fmt.Println("Event.Request.Headers:",Event.Request.Headers)
    // fmt.Println("Event.Request.Headers.Accept:",Event.Request.Headers.Accept)
    // fmt.Println("Event.Request.Headers.AcceptEncoding:",Event.Request.Headers.AcceptEncoding)
    // fmt.Println("Event.Request.Headers.AcceptLanguage:",Event.Request.Headers.AcceptLanguage)
    // ...

    fmt.Println("Source:",Event.Source)
    fmt.Println("Stash:",Event.Stash)

    
    return nil
}

享受;-)

票数 2
EN

Stack Overflow用户

发布于 2020-02-04 01:59:15

我不认为events.AppSyncResolverTemplate应该存在于传递给数据源的events对象中。

我可能错了,但我相信您在打印事件的日志中看到的是您的context.info,它显示了您的查询和您正在传递的参数。

代码语言:javascript
复制
query {
  getPerson(personId: "1")
}

这可以在lambda中用于各种原因。

您能提供更多关于您想要捕获的AppSync事件的信息吗?

你希望在那次活动中看到什么?

票数 0
EN

Stack Overflow用户

发布于 2020-02-04 18:33:13

我现在已经解决了这个问题。

事实证明,传递到无服务器lambda数据源的数据的形状是用户定义的。

在SamTemplate中,我查看了这个查询的解析器,它看起来像这样

代码语言:javascript
复制
 getPersonQueryResolver:
    Type: "AWS::AppSync::Resolver"
    Properties:
      ApiId: !GetAtt accountApi.ApiId
      TypeName: "Query"
      FieldName: "getPerson"
      DataSourceName: !GetAtt PersonDatasource.Name
      RequestMappingTemplate: |
        {
          "version" : "2017-02-28",
          "operation": "Invoke",
          "payload": {
              "field": "getPerson",
              "arguments":  $utils.toJson($context.args)
          }
        }
      ResponseMappingTemplate: |
        $utils.toJson($context.result)

我将这个解析器更改为

代码语言:javascript
复制
getPersonQueryResolver:
    Type: "AWS::AppSync::Resolver"
    Properties:
      ApiId: !GetAtt accountApi.ApiId
      TypeName: "Query"
      FieldName: "getPerson"
      DataSourceName: !GetAtt PersonDatasource.Name
      RequestMappingTemplate: |
        {
          "version" : "2017-02-28",
          "operation": "Invoke",
          "payload": $utils.toJson($context.args)
        }
      ResponseMappingTemplate: |
        $utils.toJson($context.result)

然后我将lambda代码改为

代码语言:javascript
复制
package main

import (
    "context"
    "log"

    "github.com/aws/aws-lambda-go/lambda"
)

type GetPerson struct {
    PersonID string `json:"personId"`
}

func main() {
    lambda.Start(Handler)
}

// Handler is your serverless lambda function
func Handler(ctx context.Context, event GetPerson) error {
    log.Println(ctx)
    log.Println(event)

    return nil
}

这成功地封送了事件,并将其记录为{1}

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60039002

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档