当使用 AppSync 中的 GraphQL API 时,可以通过使用 @connection 前缀指示 AppSync 为查询添加缓存支持。但是,这并不保证查询所请求的所有字段都被缓存。
为了强制缓存仅缓存查询请求的字段,可以使用 "cacheOptions" 对象中的 "forceSelections" 属性。例如:
{ "version": "2018-05-29", "operation": "GetItem", "key": { "id": $util.dynamodb.toDynamoDBJson($ctx.args.id), }, "select": $util.defaultIfNull($ctx.args.select, "ALL_ATTRIBUTES"), "cacheOptions": { "ttl": 300, "forceSelections": $ctx.args.select } }
在上述代码示例中,$ctx.args.select 表示查询请求中所请求的字段。如果客户机只请求 ItemName 和 ItemDescription 字段,则 cacheOptions 中的 forceSelections 形如:["ItemName", "ItemDescription"]。
这种方法强制缓存忽略那些未请求的字段,因此可以提高缓存命中率和应用程序的性能。