使用 Golang 从 Lambda 调用 AppSync Mutation

问题描述 投票:0回答:3

我正在尝试调用 lambda 的突变(特别是使用 golang)。我使用

AWS_IAM
作为 AppSync API 的身份验证方法。我还向我的 lambda 授予
appsync:GraphQL
权限。

但是,查看此处的文档后:https://docs.aws.amazon.com/sdk-for-go/api/service/appsync/

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

附注我不想从 lambda 查询或订阅或任何其他内容。这只是一个突变

谢谢!

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

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

现在的问题是如何使用 aws v4 签署该包中的请求?

amazon-web-services go aws-lambda aws-appsync
3个回答
3
投票

我找到了一种使用普通

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)

1
投票

问题在于该 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


0
投票

sdk v2 更新:

func SignRequest(ctx context.Context, cfg aws.Config, req *http.Request) error {
    signer := v4.NewSigner()

    hash := sha256.Sum256([]byte(""))

    cred, err := cfg.Credentials.Retrieve(ctx)
    if err != nil {
        return err
    }
    return signer.SignHTTP(ctx, cred, req, hex.EncodeToString(hash[:]), "appsync", cfg.Region, time.Now())
}

现在还有一个非官方客户端: https://github.com/sony/appsync-client-go

© www.soinside.com 2019 - 2024. All rights reserved.