How to create an Amplify subscription with a filter by record id?

Viewed 1099

I want to subscribe to changes to the specific document the user is editing. I'm trying to create the subscription and overriding the default onUpdateDocument with:

type Subscription {
  updatedDoc(id: ID!): Document @aws_subscribe(mutations: "updateDocument")
}

However I'm not getting notifications. (If I comment the custom subscription and use the deafult onUpdatedDocument then it works and I see the subscription being called when any document is updated, but I need to subscribe only to one document.

The client code to subscribe:

 (async () => {
    const opts = {
      id: currentDocument.id
    }

    console.log('Subscription opts:', opts)
    subscription = API.graphql(graphqlOperation(updatedDoc, opts)).subscribe({
      next: data => {

        console.log('subscription:',data);
      },
      error: error => {
        console.warn(error);
      }
    });
  })();

Not sure if I'm missing something here.

Note: I could filter client-side but that's not ideal for my use case.

2 Answers

I solved it, looks like the problem was with the subscription declaration.

I had mutations: "updateDocument" and it should be an array mutations: ["updateDocument"]

I also changed the name of the subscription to onUpdateDocumentWithId but don't think that's relevant.

I found an example in the docs

type Comment @model {
  id: ID!
  content: String
  postCommentsId: ID!
}

type Subscription {
  onCommentByPostId(postCommentsId: ID!): Comment
    @aws_subscribe(mutations: ["createComment"])
}
import { API } from 'aws-amplify';
import { onCommentByPostId } from './graphql/subscriptions';

API.graphql({
  query: onCommentByPostId,
  variables: {
    postCommentsId: "12345"
  }
})
.subscribe({
  next: data => {
    console.log('data: ', data)
  }
})
Related