import { Schema, z } from 'zod'; import { getNATSConnection } from '../NATS/index'; import { BaseRequestSchema, messageCodec, MethodsSchemaMap } from './common'; export class QueueClient< SubjectT extends string, MethodsSchemaMapT extends MethodsSchemaMap, ParamsSchemaT extends Schema, ReplySchemaT extends Schema > { schema: MethodsSchemaMapT; subject: SubjectT; constructor(subject: SubjectT, schema: MethodsSchemaMapT) { this.schema = schema; this.subject = subject; } async request( method: MethodKeyT, params: z.infer ): Promise> { const requestedMethodSchema = this.schema[method]; if (!requestedMethodSchema) { throw new Error( `Request method "${String(method)}" not present in methods` ); } // Parse/validate the reques const request = BaseRequestSchema.parse({ method, params: requestedMethodSchema.params.parse(params), }); // Send the method request and await the reply const natsConnection = await getNATSConnection(); const reply = await natsConnection.request( this.subject, messageCodec.encode(request) ); // Return the decoded, parsed, and validated reply return requestedMethodSchema.reply.parse(messageCodec.decode(reply.data)); } }