5

For a Chat app I am trying to update the Apollo cache for a nested array, so that when a message is received for any conversation, the user can see the latest message in real time.

Example of chat app and messages to show in real time

I have the following AppSync schema.

 type Conversation
   @model
   @auth(rules: [
     { allow: owner, ownerField: "users", operations: [create, read, delete, update] }
     { allow: private, provider: iam, operations: [read, create, update, delete] }
   ]) {
     messages: [Message] @hasMany(indexName: "messagesByConversation", limit: 1)
     users: [String]
     createdAt: AWSDateTime
     updatedAt: AWSDateTime
}

type Message
   @model(mutations: { create: "createMessage", update: "updateMessage" })
   @auth(rules: [
     { allow: groups, groups: ["Users"] }
     { allow: owner, operations: [read, create, update], ownerField: "users" }
     { allow: private, provider: iam }
   ]) {
     conversationId: ID! @index(name: "messagesByConversation", sortKeyFields: ["createdAt"], queryField: "messagesByConversation")
     text: String
     users: [String]!
     receiver: ID!
     sender: ID!
     createdAt: AWSDateTime!
     updatedAt: AWSDateTime
}

 type Subscription {
   onCreateMessageForSenderUser(sender: String!): Message @aws_subscribe(mutations: ["createMessage"])
   onCreateMessageForReceiverUser(receiver: String!): Message @aws_subscribe(mutations: ["createMessage"])
 }

Which has the nested model messages: [Message]

In the Apollo Cache, I can see a new typename is created called __ ModelMessageConnection to facilitate the connection

typename __ ModelMessageConnection

I have a subscription that listens for new messages (in this case when my user is the sender).

The trouble I am facing, is how can I update the cache so when the subscription for a new message is received, it updates for the conversation (the ModelMessageConnection)

const { data: senderMessageData } = useSubscription(
    gql(SENDER_MESSAGE_SUBSCRIPTION),
    {
      skip: !subData?.sub,
      variables: {
        sender: subData?.sub
      },
      onSubscriptionData: (options) => {
        options.client.cache.modify({
          //TODO: do something here?
        });
      }
    }
  );
Dylan w
  • 2,565
  • 1
  • 18
  • 30

0 Answers0