使用Golang从Lambda调用AppSync突变

时间:2018-10-08 02:35:12

标签: amazon-web-services go aws-lambda aws-appsync

我正在尝试从lambda调用突变(特别是使用golang)。我使用AWS_IAM作为AppSync API的身份验证方法。我还向我的Lambda授予appsync:GraphQL许可。

但是,在这里查看文档后:https://docs.aws.amazon.com/sdk-for-go/api/service/appsync/

我找不到有关如何从库中调用appsync的任何文档。有人可以在这里指出我正确的方向吗?

P.S。我不想从lambda进行查询或订阅。只是突变

谢谢!

------ 更新 -------

感谢@thomasmichaelwallace通知我使用https://godoc.org/github.com/machinebox/graphql

现在的问题是,如何使用aws v4从该软件包中签名请求?

2 个答案:

答案 0 :(得分:2)

问题在于API /库旨在帮助您创建/更新应用同步实例。

如果要实际调用它们,则需要POST到GraphQL端点。

最简单的测试方法是登录AWS AppSync控制台,按侧栏中的“查询”按钮,然后输入并运行您的突变。

我对go并不满意,但是从中我可以看到golang中有GraphQL的客户端库(例如https://godoc.org/github.com/machinebox/graphql)。

如果您使用的是IAM,则需要使用v4签名对请求进行签名(有关详细信息,请参见本文:https://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html

答案 1 :(得分:1)

我找到了一种使用普通http.Request和AWS v4签名的方法。 (感谢@thomasmichaelwallace指出了此方法)

client := new(http.Client)
// construct the query
query := AppSyncPublish{
    Query: `
        mutation ($userid: ID!) {
            publishMessage(
                userid: $userid
            ){
                userid
            }
        }
    `,
    Variables: PublishInput{
        UserID:     "wow",
    },
}
b, err := json.Marshal(&query)
if err != nil {
    fmt.Println(err)
}

// construct the request object
req, err := http.NewRequest("POST", os.Getenv("APPSYNC_URL"), bytes.NewReader(b))
if err != nil {
    fmt.Println(err)
}
req.Header.Set("Content-Type", "application/json")

// get aws credential
config := aws.Config{
    Region: aws.String(os.Getenv("AWS_REGION")),
}
sess := session.Must(session.NewSession(&config))


//sign the request
signer := v4.NewSigner(sess.Config.Credentials)
signer.Sign(req, bytes.NewReader(b), "appsync", "ap-southeast-1", time.Now())

//FIRE!!
response, _ := client.Do(req)

//print the response
buf := new(bytes.Buffer)
buf.ReadFrom(response.Body)
newStr := buf.String()

fmt.Printf(newStr)