AppSyn c Custom Resolver для подсчета записей DynamoDB - PullRequest
0 голосов
/ 13 марта 2020

У меня есть приложение React AppSyn c с ресурсами AWS, выделенными с помощью Amplify CLI. Мне нужно получить количество объектов в одной из моих таблиц, которая содержит несколько тысяч записей, без необходимости извлечения самих записей. Помимо глупости извлечения тысяч сущностей просто для их подсчета, я также сталкиваюсь с проблемой, что я все равно не могу получить все эти записи в одном запросе. Простой вызов, подобный этому:

import { API, graphqlOperation } from "aws-amplify";

const nodeData = await API.graphql(
  graphqlOperation(
    `query allNodeIds {
      listNodes(limit: 10000) {
        items {
          id
        }
      }
    }`,
    {}
  )
);

const nodeCount = nodeData.data.listNodes.items.length;

Вызывает следующую консольную ошибку:

...
errorType: "MappingTemplate"
message: "List size cannot exceed 1000"

Кажется, мне нужно написать собственный запрос и решатель для подсчета и возврата количества записей в таблицу, но не знаете, с чего начать с написания распознавателей (в VTL?), где поместить их в проект и т. д. c. Любая помощь?

EDIT : Написал распознаватель, основанный на одном из моих других сгенерированных распознавателей, но он все еще ограничен 1001 записями, хотя я установил ограничение на 9999.

Схема

...
countResponses(filter: ModelResponseFilterInput, limit: Int, nextToken: String): Int

Шаблон сопоставления запросов

#set( $limit = $util.defaultIfNull($context.args.limit, 9999) )
#set( $ListRequest = {
  "version": "2017-02-28",
  "limit": $limit
} )
#if( $context.args.nextToken )
  #set( $ListRequest.nextToken = "$context.args.nextToken" )
#end
#if( $context.args.filter )
  #set( $ListRequest.filter = $util.parseJson("$util.transform.toDynamoDBFilterExpression($ctx.args.filter)") )
#end
#if( !$util.isNull($modelQueryExpression)
                        && !$util.isNullOrEmpty($modelQueryExpression.expression) )
  $util.qr($ListRequest.put("operation", "Query"))
  $util.qr($ListRequest.put("query", $modelQueryExpression))
  #if( !$util.isNull($ctx.args.sortDirection) && $ctx.args.sortDirection == "DESC" )
    #set( $ListRequest.scanIndexForward = false )
  #else
    #set( $ListRequest.scanIndexForward = true )
  #end
#else
  $util.qr($ListRequest.put("operation", "Scan"))
#end
$util.toJson($ListRequest)

Шаблон сопоставления ответов

## [Start] Determine request authentication mode **
#if( $util.isNullOrEmpty($authMode) && !$util.isNull($ctx.identity) && !$util.isNull($ctx.identity.sub) && !$util.isNull($ctx.identity.issuer) && !$util.isNull($ctx.identity.username) && !$util.isNull($ctx.identity.claims) && !$util.isNull($ctx.identity.sourceIp) && !$util.isNull($ctx.identity.defaultAuthStrategy) )
  #set( $authMode = "userPools" )
#end
## [End] Determine request authentication mode **
## [Start] Check authMode and execute owner/group checks **
#if( $authMode == "userPools" )
  ## No Static Group Authorization Rules **


  ## [Start] If not static group authorized, filter items **
  #if( !$isStaticGroupAuthorized )
    #set( $count = 0 )
    #foreach( $item in $ctx.result.items )
      ## No Dynamic Group Authorization Rules **


      ## [Start] Owner Authorization Checks **
      #set( $isLocalOwnerAuthorized = false )
      ## Authorization rule: { allow: owner, ownerField: "owner", identityClaim: "cognito:username" } **
      #set( $allowedOwners0 = $item.owner )
      #set( $identityValue = $util.defaultIfNull($ctx.identity.claims.get("username"), $util.defaultIfNull($ctx.identity.claims.get("cognito:username"), "___xamznone____")) )
      #if( $util.isList($allowedOwners0) )
        #foreach( $allowedOwner in $allowedOwners0 )
          #if( $allowedOwner == $identityValue )
            #set( $isLocalOwnerAuthorized = true )
          #end
        #end
      #end
      #if( $util.isString($allowedOwners0) )
        #if( $allowedOwners0 == $identityValue )
          #set( $isLocalOwnerAuthorized = true )
        #end
      #end
      ## [End] Owner Authorization Checks **


      #if( ($isLocalDynamicGroupAuthorized == true || $isLocalOwnerAuthorized == true) )
        #set( $count = $count + 1)
      #end
    #end
    #set( $ctx = $count )
  #end
  ## [End] If not static group authorized, filter items **
#end
## [End] Check authMode and execute owner/group checks **

$util.toJson($ctx)
...