4

我正在使用 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 中。

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

4

1 回答 1

1

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

->在你的 Schema中:在 中添加这个type Query,然后点击“Save Schema”:

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

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

  • 选择TrackTable作为您的数据源名称

  • 请求映射模板

#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)

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

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
        }
      ]
    }
  }
}

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

于 2019-03-12T01:04:29.903 回答