amplify-category-api icon indicating copy to clipboard operation
amplify-category-api copied to clipboard

onUpdate Subscription throwing client errors

Open kekami opened this issue 9 months ago • 2 comments

Environment information

System:
  OS: macOS 14.4.1
  CPU: (10) arm64 Apple M1 Max
  Memory: 170.11 MB / 32.00 GB
  Shell: /bin/zsh
Binaries:
  Node: 20.12.2 - ~/.nvm/versions/node/v20.12.2/bin/node
  Yarn: 3.8.2 - ~/.nvm/versions/node/v20.12.2/bin/yarn
  npm: 10.5.0 - ~/.nvm/versions/node/v20.12.2/bin/npm
  pnpm: undefined - undefined
NPM Packages:
  @aws-amplify/backend: 1.0.1
  @aws-amplify/backend-cli: 1.0.2
  aws-amplify: 6.2.0
  aws-cdk: 2.141.0
  aws-cdk-lib: 2.141.0
  typescript: 5.3.3
AWS environment variables:
  AWS_SDK_LOAD_CONFIG = 1
  AWS_STS_REGIONAL_ENDPOINTS = regional
  AWS_NODEJS_CONNECTION_REUSE_ENABLED = 1
No CDK environment variables

Description

Having issues getting subscription to work, when trying out the .onUpdate() subscription, I'm getting the following error message on the client. It works in the AppSync console.

TypeError: Cannot read properties of null (reading 'id')
    at APIClient.mjs:146:73
    at Array.map (<anonymous>)
    at APIClient.mjs:146:36
    at Array.map (<anonymous>)
    at initializeModel (APIClient.mjs:38:20)
    at subscription.mjs:23:12
    at map.js:9:7
    at OperatorSubscriber._this._next (OperatorSubscriber.js:18:21)
    at Subscriber.next (Subscriber.js:36:6)
    at Subscriber._next (Subscriber.js:65:16)

kekami avatar May 12 '24 19:05 kekami

I debugged this. Problem can be found in:

@aws-amplify/data-schema/dist/esm/runtime/internals/operations/subscription.mjs

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
function subscriptionFactory(client, modelIntrospection, model, operation, getInternals) {
    const { name } = model;
    const subscription = (args) => {
        const query = generateGraphQLDocument(modelIntrospection, name, operation, args);
        const variables = buildGraphQLVariables(model, operation, args, modelIntrospection);
        const auth = authModeParams(client, getInternals, args);
        const headers = getCustomHeaders(client, getInternals, args?.headers);
        const observable = client.graphql({
            ...auth,
            query,
            variables,
        }, headers);
>>        return observable.pipe(map((value) => { <<<<< value contained { onEmployeeUpdate: { data: null, errors: [bunch of errrors] } }
            const [key] = Object.keys(value.data);
>>            const data = value.data[key];  <<<<< null
            const [initialized] = initializeModel(client, name, [data], modelIntrospection, auth.authMode, auth.authToken);
            return initialized;
        }));
    };
    return subscription;
}

The errors were essentially that createdAt, updatedAt, owner can't be null.

So a workaround was to change my mutation from

updateEmployee(input: $input) {
  id
  firstName
  lastName
}

to

updateEmployee(input: $input) {
  id
  createdAt
  updatedAt
  owner
  firstName
  lastName
}

If you need anything else don't hesitate to ping me

kekami avatar May 14 '24 13:05 kekami

You might be wondering as well why I'm using updateEmployee. It's because I'm triggering it from EventBridge, e.g.

new aws_events.CfnRule(this, 'subscription', {
      eventBusName: props.eventBus.eventBusName,
      eventPattern: {
        'source': ['com.*****'],
        'detail-type': ['identity-verification.status'],
        'detail': {
          verifieraResult: {
            score: [{ numeric: ['=', 0] }],
          },
        },
      },
      roleArn: eventBusRole.roleArn,
      targets: [
        {
          id: 'appsyncBroadcastReceiver',
          arn: props.attrGraphQlEndpointArn,
          roleArn: eventBusRole.roleArn,
          appSyncParameters: {
            graphQlOperation: `
              mutation UpdateEmployeIdentityVerification($input: UpdateEmployeeInput!) {
                updateEmployee(input: $input) {
                  id
                  createdAt
                  updatedAt
                  owner
                  firstName
                  lastName
                }
              }`,
          },
          inputTransformer: {
            inputPathsMap: {
              id: '$.detail.userId',
              firstName: '$.detail.**********.firstName',
              lastName: '$.detail..**********.lastName',
            },
            inputTemplate: JSON.stringify({
              input: {
                id: '<id>',
                firstName: '<firstName>',
                lastName: '<lastName>',
              },
            }),
          },
        },
      ],
    });

kekami avatar May 14 '24 13:05 kekami

Hi @kekami reading the issue description, this sounds like the issue was with the hand written mutation in the EventBridge CDK code's selection set not matching the subscription's? You might have been able to adjust the selection set on the subscription itself like so:

await client.models.Employee.onUpdate({
  selectionSet: ["id", "firstName", "lastName"],
});

chrisbonifacio avatar May 20 '24 18:05 chrisbonifacio

Hi @kekami reading the issue description, this sounds like the issue was with the hand written mutation in the EventBridge CDK code's selection set not matching the subscription's? You might have been able to adjust the selection set on the subscription itself like so:


await client.models.Employee.onUpdate({

  selectionSet: ["id", "firstName", "lastName"],

});

Hey @chrisbonifacio,sorry for the late reply. Yes it was the handwritten mutation that was the cause. But I guess this issue is more for the unhandled throw and unspecific error message. Had to drop down to amplify source to understand what was going on.

kekami avatar May 27 '24 13:05 kekami

@kekami No worries, thanks for confirming! I'm going to close this issue as you're unblocked but we will look into adding a callout in the docs that mentions this error message to improve discoverability.

https://github.com/aws-amplify/docs/issues/7680

chrisbonifacio avatar May 29 '24 20:05 chrisbonifacio

This issue is now closed. Comments on closed issues are hard for our team to see. If you need more assistance, please open a new issue that references this one.

github-actions[bot] avatar May 29 '24 20:05 github-actions[bot]