aws appsyn c подписки не срабатывают - PullRequest
0 голосов
/ 10 июля 2020

Я уже некоторое время борюсь с этим, поэтому мне нужна помощь.

Я не могу получить подписку onCreate для типа HealthPlan, работающего в моем приложении, поддерживающем реакцию.

На основе примера Надера :

schema.graphql

type HealthPlan {
    id: ID!
    name: String!
    type: String!
    owner: String
}

input CreateHealthPlanInput {
    name: String!
    type: String!
}

type Mutation {
    ....
    createHealthPlan(input: CreateHealthPlanInput!): HealthPlan
    ...
}

type Subscription {
    ...
    onCreateHealthPlan(owner: String!): HealthPlan
        @aws_subscribe(mutations: ["createHealthPlan"])
    ...
}

мутаций. js

export const createHealthPlan = /* GraphQL */ `
  mutation CreateHealthPlan($input: CreateHealthPlanInput!) {
    createHealthPlan(input: $input) {
      id
      name
      type
      owner
    }
  }
`;

подписок. js

export const onCreateHealthPlan = /* GraphQL */ `
  subscription OnCreateHealthPlan($owner: String!) {
    onCreateHealthPlan(owner: $owner) {
      id
      name
      type
      owner
    }
  }
`;

Основная. js

import { API, graphqlOperation } from 'aws-amplify';
import { onCreateHealthPlan } from './subscriptions.js';

const sub = "cognitoSubField";   // AMAZON_COGNITO_USER_POOLS auth

API.graphql(
          graphqlOperation(onCreateHealthPlan, {
            owner: sub,
          }),
        ).subscribe({
          next: response => {
            console.log('next data received', response);
          },
          error: err => {
            console.log('subscription error', err.message);
          },
          complete: () => {
            console.log('finished');
          },
})

Mutation.createHealthPlan.req.vtl

## [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 **


  ## No Dynamic Group Authorization Rules **


  ## [Start] Owner Authorization Checks **
  #set( $isOwnerAuthorized = false )
  ## Authorization rule: { allow: owner, ownerField: "owner", identityClaim: "cognito:username" } **
  #set( $allowedOwners0 = $util.defaultIfNull($ctx.args.input.owner, null) )
  #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( $isOwnerAuthorized = true )
      #end
    #end
  #end
  #if( $util.isString($allowedOwners0) )
    #if( $allowedOwners0 == $identityValue )
      #set( $isOwnerAuthorized = true )
    #end
  #end
  #if( $util.isNull($allowedOwners0) && (! $ctx.args.input.containsKey("owner")) )
    $util.qr($ctx.args.input.put("owner", $identityValue))
    #set( $isOwnerAuthorized = true )
  #end
  ## [End] Owner Authorization Checks **


  ## [Start] Throw if unauthorized **
  #if( !($isStaticGroupAuthorized == true || $isDynamicGroupAuthorized == true || $isOwnerAuthorized == true) )
    $util.unauthorized()
  #end
  ## [End] Throw if unauthorized **
#end
## [End] Check authMode and execute owner/group checks **


## [Start] Prepare DynamoDB PutItem Request. **
$util.qr($context.args.input.put("createdAt", $util.defaultIfNull($ctx.args.input.createdAt, $util.time.nowISO8601())))
$util.qr($context.args.input.put("updatedAt", $util.defaultIfNull($ctx.args.input.updatedAt, $util.time.nowISO8601())))
$util.qr($context.args.input.put("__typename", "HealthPlan"))
#set( $condition = {
  "expression": "attribute_not_exists(#id)",
  "expressionNames": {
      "#id": "id"
  }
} )
#if( $context.args.condition )
  #set( $condition.expressionValues = {} )
  #set( $conditionFilterExpressions = $util.parseJson($util.transform.toDynamoDBConditionExpression($context.args.condition)) )
  $util.qr($condition.put("expression", "($condition.expression) AND $conditionFilterExpressions.expression"))
  $util.qr($condition.expressionNames.putAll($conditionFilterExpressions.expressionNames))
  $util.qr($condition.expressionValues.putAll($conditionFilterExpressions.expressionValues))
#end
#if( $condition.expressionValues && $condition.expressionValues.size() == 0 )
  #set( $condition = {
  "expression": $condition.expression,
  "expressionNames": $condition.expressionNames
} )
#end
{
  "version": "2017-02-28",
  "operation": "PutItem",
  "key": #if( $modelObjectKey ) $util.toJson($modelObjectKey) #else {
  "id":   $util.dynamodb.toDynamoDBJson($util.defaultIfNullOrBlank($ctx.args.input.id, $util.autoId()))
} #end,
  "attributeValues": $util.dynamodb.toMapValuesJson($context.args.input),
  "condition": $util.toJson($condition)
}
## [End] Prepare DynamoDB PutItem Request. **

Mutation.createHealthPlan.res.vtl

$util.toJson($ctx.result)

Subscription.onCreateHealthPlan. req.vtl

{
    "version": "2018-05-29",
    "payload": {}
}

Subscription.onCreateHealthPlan.res.vtl

## [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] Owner Authorization Checks **
  #set( $isOwnerAuthorized = false )
  ## Authorization rule: { allow: owner, ownerField: "owner", identityClaim: "cognito:username" } **
  #set( $allowedOwners0 = $util.defaultIfNull($ctx.args.owner, null) )
  #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( $isOwnerAuthorized = true )
      #end
    #end
  #end
  #if( $util.isString($allowedOwners0) )
    #if( $allowedOwners0 == $identityValue )
      #set( $isOwnerAuthorized = true )
    #end
  #end
  ## [End] Owner Authorization Checks **


  ## [Start] Throw if unauthorized **
  #if( !($isStaticGroupAuthorized == true || $isOwnerAuthorized == true) )
    $util.unauthorized()
  #end
  ## [End] Throw if unauthorized **
#end
## [End] Check authMode and execute owner/group checks **

$util.toJson(null)

Каждый раз при запуске кода я получаю:

subscription error

зарегистрирован в консоли.

Анализируя вывод консоли, я обнаружил следующую информацию:

LOG  [DEBUG] 39:51.456 AWSAppSyncRealTimeProvider - subscription message from AWS AppSyncRealTime: {"type":"connection_ack","payload":{"connectionTimeoutMs":300000}}
LOG  [DEBUG] 39:51.457 AWSAppSyncRealTimeProvider - Notifying connection successful
LOG  [DEBUG] 39:51.459 AWSAppSyncRealTimeProvider - subscription message from AWS AppSync RealTime: {"type":"ka"}
LOG  [DEBUG] 39:51.459 AWSAppSyncRealTimeProvider {"id": "", "observer": null, "query": "", "variables": {}}
LOG  [DEBUG] 39:51.620 AWSAppSyncRealTimeProvider - subscription message from AWS AppSync RealTime: {"id":"9f72da89-0d1d-4aa8-8457-78bb1832478b","type":"error","payload":{"errors":[{"errorType":"MappingTemplate","message":"Value for field '$[operation]' not found."}]}}
LOG  [DEBUG] 39:51.620 AWSAppSyncRealTimeProvider {"id": "guid", "observer": {"_subscription": {"_cleanup": [Function anonymous], "_observer": [Object], "_queue": undefined, "_state": "ready"}}, "query": "subscription OnCreateHealthPlan($owner: String!) {                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
    onCreateHealthPlan(owner: $owner) {
        id
        name
        type
        owner                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
    }                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     }", "variables": {"owner": "cognitoSubField"}}
LOG  [DEBUG] 39:51.622 AWSAppSyncRealTimeProvider - Error while unsubscribing Error: Subscription never connected
LOG  [DEBUG] 39:52.624 AWSAppSyncRealTimeProvider - closing WebSocket...

Похоже, что это настоящая ошибка : Value for field '$[operation]' not found

Есть идеи, почему это происходит? ?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...