thang an pha qua

This commit is contained in:
2024-11-08 15:15:59 +07:00
parent 57037a59ec
commit 1897ccf677
4 changed files with 43 additions and 12 deletions

View File

@@ -40,8 +40,6 @@ import { WorkshopOrganizationModule } from '../WorkshopOrganization/workshoporga
import { WorkshopSubscriptionModule } from '../WorkshopSubscription/workshopsubscription.module'
import { initContextCache } from '@pothos/core'
import { PubSub } from 'graphql-subscriptions'
import { isSubscription } from 'rxjs/internal/Subscription'
import { EventEmitter } from 'ws'
@Global()
@Module({
@@ -90,7 +88,6 @@ import { EventEmitter } from 'ws'
debug: process.env.NODE_ENV === 'development' || false,
playground: process.env.NODE_ENV === 'development' || false,
introspection: process.env.NODE_ENV === 'development' || false,
installSubscriptionHandlers: true,
subscriptions: {
'graphql-ws': true,
},
@@ -100,6 +97,7 @@ import { EventEmitter } from 'ws'
extra,
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
}: { req?: Request; subscriptions?: any; extra?: any }) => {
initContextCache()
if (subscriptions) {
return {
isSubscription: true,
@@ -148,10 +146,7 @@ import { EventEmitter } from 'ws'
},
{
provide: 'PUB_SUB',
useFactory: () =>
new PubSub({
eventEmitter: new EventEmitter({}),
}),
useFactory: () => new PubSub(),
},
],
exports: [

View File

@@ -147,6 +147,7 @@ export class MessageSchema extends PothosSchema {
'senderId',
'sender',
'sentAt',
'context',
]),
description: 'The message to send.',
required: true,
@@ -156,6 +157,7 @@ export class MessageSchema extends PothosSchema {
if (ctx.isSubscription) {
throw new Error('Not allowed')
}
const messageContext = MessageContextType.CHAT
// get the sender from the context and add it to the input
args.input.sender = {
connect: {
@@ -165,6 +167,7 @@ export class MessageSchema extends PothosSchema {
if (!args.input.sender) {
throw new Error('Cannot get sender from context')
}
args.input.context = messageContext
const message = await this.prisma.message.create({
...query,
data: args.input,
@@ -172,7 +175,7 @@ export class MessageSchema extends PothosSchema {
if (ctx.isSubscription) {
throw new Error('Not allowed')
}
ctx.http.pubSub.publish('MESSAGE_SENT', message)
ctx.http.pubSub.publish(`MESSAGE_SENT_${message.chatRoomId}`, message)
return message
},
}),
@@ -182,13 +185,19 @@ export class MessageSchema extends PothosSchema {
messageSent: t.field({
description: 'Subscribe to messages sent by users.',
type: this.message(),
subscribe: (_, __, ctx: SchemaContext) => {
args: {
chatRoomId: t.arg({
type: 'String',
description: 'The ID of the chat room to subscribe to.',
}),
},
subscribe: (_, args, ctx: SchemaContext) => {
if (!ctx.isSubscription) throw new Error('Not allowed')
const {
websocket: { pubSub },
} = ctx
return pubSub.asyncIterator(
'MESSAGE_SENT',
`MESSAGE_SENT_${args.chatRoomId}`,
) as unknown as AsyncIterable<Message>
},
resolve: (payload: Message) => payload,