Search code examples
graphqlaws-appsyncaws-amplify

AppSync/Amplify - how to define GraphQL subscriptions


I am using Amplify to auto-generate queries, mutations and subscriptions. and I have this type:

type Message @model {  
  id: ID!
  author: User @connection(name: "UserMessages")
  content: String
}

How do I add authorID as a filter to subscriptions for new messages using Amplify generated schema?


Solution

  • You may add your own subscription fields that are parameterized however you like.

    Try this

    # Add the authorId explicitly and turn off the generated subscriptions.
    type Message @model(subscriptions: null) {  
      id: ID!
      author: User @connection(name: "UserMessages")
      authorId: String
      content: String
    }
    type Subscription {
      onCreateMessage(authorId: String!): Message @aws_subscribe(mutations: "createMessage")
    }
    

    Subscribed clients only get messages with the authorId provided in the subscription query:

    subscription SubscribeToNewMessages($id: String!) {
      onCreateMessage(authorId: $id) {
        id
        authorId
        content
      }
    }