从AWS-Amplify中的Lambda函数查询和变异GraphQL,使用Cognito for auth

时间:2020-02-03 17:43:55

标签: aws-lambda aws-amplify aws-amplify-cli

我通过amplify api add命令创建了一个GraphQL api,并添加了以下架构。我正在使用Cognito进行身份验证。

type User @model
  @auth(rules: [{ allow: owner }]) {
  id: ID!

  videos: [Video!] @connection(keyName: "videosByUser", fields: ["id"])
  adverts: [Advert] @connection(keyName:"advertsByUser", fields: ["id"])
}

type Video @model
  @key(name: "videosByUser", fields: ["userId"])
  @auth(rules: [{ allow: owner, operations: [create, update, delete] }]) {

  id: ID!
  title: String!
  description: String!

  size: Float!
  length: Float!
  hashMarks: [Float!]!

  userId: ID!
  # bidrectional connection, if needed
  # user: User! @connection(fields: ["userId"])

  adverts: [VideoAdverts!] @connection(keyName: "advertsByVideo", fields: ["id"])
  streamingLink: AWSURL
}

type VideoAdverts @model(queries: null)
  @key(name: "advertsByVideo", fields: ["videoId", "advertId"])
  @key(name: "videosByAdvert", fields: ["advertId", "videoId"]) {

  id: ID!
  videoId: ID!
  advertId: ID!

  video: Video! @connection(fields: ["videoId"])
  advert: Advert! @connection(fields: ["advertId"])
}

type Advert @model
  @key(name: "advertsByUser", fields: ["userId"])
  @auth(rules: [{ allow: owner, operations: [create, update, delete] }]) {

  id: ID!
  title: String!
  description: String!

  size: Float!
  length: Float!

  creatorId: ID!
  # bidrectional connection, if needed
  # creator: Creator! @connection(fields: ["creatorId"])

  videos: [VideoAdverts!] @connection(keyName: "videosByAdvert", fields: ["id"])
  blacklist: [AdvertBlacklist!] @connection(keyName: "blacklistByAdvert", fields: ["id"])

  startDate: AWSDateTime
  endDate: AWSDateTime
}

这是我的第一个扩增项目,我在弄清楚如何实现以下用例时遇到困难:

  1. 使用lambda函数查询数据并返回到客户端。
  2. 使用cron触发的lambda函数进行API调用,并使用变异来更新某些字段。

到目前为止,我发现所有与谷歌搜索无关的事情都涉及使用lambda与通过amplify storage add命令添加的数据进行交互。

我在Stackoverflow上找到的其他一些示例未将cognito用于身份验证。

看起来我将能够使用cloudwatch触发lambda,因此,我现在的主要问题是如何使用cognito进行身份验证,如何从lambda中实际查询和变异GraphQL api。 任何帮助都将非常有帮助,谢谢:)

1 个答案:

答案 0 :(得分:1)

对Lambda函数进行身份验证以与AppSync API进行交互的关键是配置多种身份验证方法。您正在为前端应用程序用户使用Cognito,但是,您不想将其用于Lambda函数身份验证。 AppSync支持您的API的多种身份验证机制。在您的情况下,您将需要添加IAM作为第二种身份验证机制。

您可以通过Amplify CLI执行此操作:

$ amplify update api

Scanning for plugins...
Plugin scan successful

? Please select from one of the below mentioned services: GraphQL

? Choose the default authorization type for the API Amazon Cognito User Pool
Use a Cognito user pool configured as a part of this project.

? Do you want to configure advanced settings for the GraphQL API Yes, I want 
to make some additional changes.

? Configure additional auth types? Yes

? Choose the additional authorization types you want to configure for the API IAM