如何在AppSync / Amplify中过滤非标量类型

问题描述 投票:1回答:1

我使用aws-amplify来定义我的appsync架构。

我有以下简化架构:

type Country @model {
  id: ID!
  name: String!
  code: String!
  tracks: [Track] @connection(name: "CountryTrack")
}

type Track @model
  id: ID!
  name: String!
  country: Country! @connection(name: "CountryTrack")
  lng: Float
  lat: Float
  length: Float
  curves: Int
  website: String
  trackImage: String
  information: String
}

Amplify为模型生成FilterInput。但是它不包括连接类型。

我想根据国家/地区过滤跟踪。

dynamodb表确实有trackCountryId,在扫描操作中我可以根据id进行简单过滤。

但是这在graphql架构中不起作用。因为trackCountryId不包含在FiterInput中。

有谁知道如何解决这个问题?

amazon-web-services amazon-dynamodb aws-appsync aws-amplify amplifyjs
1个回答
1
投票

Amplify CLI在listTracks类型上创建tracks查询+解析器和Country解析器,开箱即用。如果您想根据countryId过滤所有曲目,则必须在以下步骤中手动添加此曲目,这些步骤基本上是上面生成的查询+解析器的混合:

- >在你的Schema中:在type Query中添加它,然后单击“Save Schema”:

listTracksByCountry(countryId: ID!, limit: Int, nextToken: String, sortDirection: ModelSortDirection): ModelTrackConnection

- >将解析器附加到刚添加的此查询字段,然后单击“保存解析器”:

  • 选择TrackTable作为您的数据源名称
  • RequestMapping模板:
#set( $limit = $util.defaultIfNull($context.args.limit, 10) )
{
  "version": "2017-02-28",
  "operation": "Query",
  "query": {
      "expression": "#connectionAttribute = :connectionAttribute",
      "expressionNames": {
          "#connectionAttribute": "trackCountryId"
    },
      "expressionValues": {
          ":connectionAttribute": {
              "S": "$context.args.countryId"
      }
    }
  },
  "scanIndexForward":   #if( $context.args.sortDirection )
    #if( $context.args.sortDirection == "ASC" )
true
    #else
false
    #end
  #else
true
  #end,
  "filter":   #if( $context.args.filter )
$util.transform.toDynamoDBFilterExpression($ctx.args.filter)
  #else
null
  #end,
  "limit": $limit,
  "nextToken":   #if( $context.args.nextToken )
"$context.args.nextToken"
  #else
null
  #end,
  "index": "gsi-CountryTrack"
}
  • 响应映射模板:
#if( !$result )
  #set( $result = $ctx.result )
#end
$util.toJson($result)

- >导航到控制台上的Queries部分,然后运行以下查询:

query {
  listTracksByCountry(countryId: "countryId1") {
    items {
      id
      name
      length
    }
  }
}

您应该能够获得指定countryId的曲目列表。在我的例子中,上述操作的GraphQL输出是:

{
  "data": {
    "listTracksByCountry": {
      "items": [
        {
          "id": "trackId1",
          "name": "track name 1",
          "length": 1.1
        },
        {
          "id": "trackId2",
          "name": "track name 2",
          "length": 1.2
        }
      ]
    }
  }
}

这似乎是一个非常常见的用例,所以随意创建一个问题here,如果它已经不存在,我们可以使用Amplify CLI(amplify add api),自动生成这些解析器。

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