diff --git a/backend/src/schema/resolvers/messages.ts b/backend/src/schema/resolvers/messages.ts index e7651f613..785b8d99c 100644 --- a/backend/src/schema/resolvers/messages.ts +++ b/backend/src/schema/resolvers/messages.ts @@ -1,6 +1,6 @@ import { neo4jgraphql } from 'neo4j-graphql-js' import Resolver from './helpers/Resolver' -import RoomResolver from './rooms' +import { getUnreadRoomsCount } from './rooms' import { pubsub, ROOM_COUNT_UPDATED } from '../../server' export default { @@ -90,16 +90,16 @@ export default { record.get('message'), ) - // TODO change user in context - mark message as seen - chattingUser is the correct user. - const roomCountUpdated = await RoomResolver.Query.UnreadRooms(null, null, context, null) - - // send subscriptions - await pubsub.publish(ROOM_COUNT_UPDATED, { roomCountUpdated, user: message.otherUser }) - return message }) try { const message = await writeTxResultPromise + + const roomCountUpdated = await getUnreadRoomsCount(currentUserId, session) + + // send subscriptions + await pubsub.publish(ROOM_COUNT_UPDATED, { roomCountUpdated, user: message.otherUser }) + return message } catch (error) { throw new Error(error) diff --git a/backend/src/schema/resolvers/rooms.ts b/backend/src/schema/resolvers/rooms.ts index 6774dad98..029b44b94 100644 --- a/backend/src/schema/resolvers/rooms.ts +++ b/backend/src/schema/resolvers/rooms.ts @@ -3,6 +3,18 @@ import Resolver from './helpers/Resolver' import { pubsub, ROOM_COUNT_UPDATED } from '../../server' import { withFilter } from 'graphql-subscriptions' +export const getUnreadRoomsCount = async (userId, session) => { + return session.readTransaction(async (transaction) => { + const unreadRoomsCypher = ` + MATCH (:User { id: $userId })-[:CHATS_IN]->(room:Room)<-[:INSIDE]-(message:Message)<-[:CREATED]-(sender:User) + WHERE NOT sender.id = $userId AND NOT message.seen + RETURN toString(COUNT(DISTINCT room)) AS count + ` + const unreadRoomsTxResponse = await transaction.run(unreadRoomsCypher, { userId }) + return unreadRoomsTxResponse.records.map((record) => record.get('count'))[0] + }) +} + export default { Subscription: { roomCountUpdated: { @@ -27,17 +39,8 @@ export default { user: { id: currentUserId }, } = context const session = context.driver.session() - const readTxResultPromise = session.readTransaction(async (transaction) => { - const unreadRoomsCypher = ` - MATCH (:User { id: $currentUserId })-[:CHATS_IN]->(room:Room)<-[:INSIDE]-(message:Message)<-[:CREATED]-(sender:User) - WHERE NOT sender.id = $currentUserId AND NOT message.seen - RETURN toString(COUNT(DISTINCT room)) AS count - ` - const unreadRoomsTxResponse = await transaction.run(unreadRoomsCypher, { currentUserId }) - return unreadRoomsTxResponse.records.map((record) => record.get('count'))[0] - }) try { - const count = await readTxResultPromise + const count = await getUnreadRoomsCount(currentUserId, session) return count } finally { session.close()