From a0006f73acc2364ac5528f96cb2cff329eb700f3 Mon Sep 17 00:00:00 2001 From: ankitsridhar16 Date: Fri, 20 Jan 2023 14:55:26 +0530 Subject: [PATCH] chore: added message types to PubSub Service --- .../src/pubsub/pubsub.service.ts | 6 +++++- .../src/pubsub/subscriptionTopicsDefs.ts | 14 ++++++++++++++ .../{primitive-types.ts => primitiveTypes.ts} | 0 3 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 packages/hoppscotch-backend/src/pubsub/subscriptionTopicsDefs.ts rename packages/hoppscotch-backend/src/types/{primitive-types.ts => primitiveTypes.ts} (100%) diff --git a/packages/hoppscotch-backend/src/pubsub/pubsub.service.ts b/packages/hoppscotch-backend/src/pubsub/pubsub.service.ts index 475768712..854ef2e92 100644 --- a/packages/hoppscotch-backend/src/pubsub/pubsub.service.ts +++ b/packages/hoppscotch-backend/src/pubsub/pubsub.service.ts @@ -4,6 +4,7 @@ import { default as Redis, RedisOptions } from 'ioredis'; import { RedisPubSub } from 'graphql-redis-subscriptions'; import { PubSub as LocalPubSub } from 'graphql-subscriptions'; +import { MessageType } from './subscriptionTopicsDefs'; /** * RedisPubSub uses JSON parsing for back and forth conversion, which loses Date objects, hence this reviver brings them back @@ -70,7 +71,10 @@ export class PubSubService implements OnModuleInit { return this.pubsub.asyncIterator(topic, options); } - async publish(topic: string, payload: any) { + async publish( + topic: T, + payload: MessageType[T], + ) { await this.pubsub.publish(topic, payload); } } diff --git a/packages/hoppscotch-backend/src/pubsub/subscriptionTopicsDefs.ts b/packages/hoppscotch-backend/src/pubsub/subscriptionTopicsDefs.ts new file mode 100644 index 000000000..c860d55a4 --- /dev/null +++ b/packages/hoppscotch-backend/src/pubsub/subscriptionTopicsDefs.ts @@ -0,0 +1,14 @@ +import { UserEnvironment } from '../user-environment/user-environments.model'; +import { PrimitiveTypes } from '../types/primitiveTypes'; + +// A custom message type that defines the topic and the corresponding payload. +// For every module that publishes a subscription add its type def and the possible subscription type. +export type MessageType = { + [ + topic: `user_environment/${string}/${ + | 'created' + | 'updated' + | 'deleted' + | 'deleted_many'}` + ]: UserEnvironment | PrimitiveTypes; // Returning a number hence having a union with `PrimitiveTypes`. +}; diff --git a/packages/hoppscotch-backend/src/types/primitive-types.ts b/packages/hoppscotch-backend/src/types/primitiveTypes.ts similarity index 100% rename from packages/hoppscotch-backend/src/types/primitive-types.ts rename to packages/hoppscotch-backend/src/types/primitiveTypes.ts