This commit is contained in:
2024-11-09 18:44:35 +07:00
parent 2736547b84
commit 95a092cec9
5 changed files with 61 additions and 4 deletions

View File

@@ -7,7 +7,12 @@ import {
} from '@smatch-corp/nestjs-pothos'
import { Builder, SchemaContext } from '../Graphql/graphql.builder'
import { PrismaService } from '../Prisma/prisma.service'
import { Message, MessageContextType, MessageType } from '@prisma/client'
import {
ChatRoomType,
Message,
MessageContextType,
MessageType,
} from '@prisma/client'
import { DateTimeUtils } from '../common/utils/datetime.utils'
import { PubSubEvent } from '../common/pubsub/pubsub-event'
@@ -139,6 +144,25 @@ export class MessageSchema extends PothosSchema {
if (!args.input.sender) {
throw new Error('Cannot get sender from context')
}
let userIds: string[] = []
// get the recipient if messageContext is CHAT
if (messageContext === MessageContextType.CHAT) {
// get chatRoomId from input
const chatRoomId = args.input.chatRoom?.connect?.id
if (!chatRoomId) {
throw new Error('Cannot get chatRoomId from input')
}
// if chatroom type is SUPPORT, user 1 is mentorId, user 2 is customerId
// query the chatRoom to get the userIds
const chatRoom = await this.prisma.chatRoom.findUnique({
where: {
id: chatRoomId,
},
})
if (chatRoom?.type === ChatRoomType.SUPPORT) {
userIds = [chatRoom.mentorId!, chatRoom.customerId!]
}
}
// check if content is empty
if (!args.input.content || args.input.content.trim() === '') {
throw new Error('Content cannot be empty')
@@ -156,6 +180,13 @@ export class MessageSchema extends PothosSchema {
`${PubSubEvent.MESSAGE_SENT}.${message.chatRoomId}`,
message,
)
// publish to new message subscribers
userIds.forEach((userId: string) => {
ctx.http.pubSub.publish(
`${PubSubEvent.NEW_MESSAGE}.${userId}`,
message,
)
})
return message
},
}),
@@ -176,9 +207,9 @@ export class MessageSchema extends PothosSchema {
const {
websocket: { pubSub },
} = ctx
return pubSub.asyncIterator(
return pubSub.asyncIterator([
`${PubSubEvent.MESSAGE_SENT}.${args.chatRoomId}`,
) as unknown as AsyncIterable<Message>
]) as unknown as AsyncIterable<Message>
},
resolve: (payload: Message) => payload,
}),