import update from "immutability-helper" ; import { scrollToBottom } from "utils" ; import { Me , Message as IMessage , OnUpdateMessageDocument , OnDeleteMessageDocument , OnNewMessageDocument , GetRoomQuery , } from "graphql/generated/graphql" ; const subscribeToMessages = ( subscribeToMore , variables , user , bodyRef ) => { subscribeToMore ( { variables : variables , document : OnNewMessageDocument , updateQuery : ( prev , data ) => { const newData = data . subscriptionData ; const newMessage = newData . data . onNewMessage ; if ( ! newMessage || newMessage . author . id === user . id ) return prev ; window . setTimeout ( ( ) => { scrollToBottom ( bodyRef ?. current ) ; } , 50 ) ; return update ( prev , { messages : { edges : { $push : [ { __typename : "MessageEdge" , node : newMessage , cursor : newMessage . id , } , ] , } , } , } ) ; } , } ) ; subscribeToMore ( { variables : variables , document : OnDeleteMessageDocument , updateQuery : ( prev , data ) => { const newData = data . subscriptionData ; const deletedMessage = newData . data . onDeleteMessage ; if ( ! deletedMessage || deletedMessage . author . id === user . id ) { return prev ; } return update ( prev , { messages : { edges : e => e . filter ( edge => edge . node . id !== deletedMessage . id ) , } , } ) ; } , } ) ; subscribeToMore ( { variables : variables , document : OnUpdateMessageDocument , } ) ; } ; export default subscribeToMessages ;