| 1 | import type { MetadataScanner, ModulesContainer } from '@nestjs/core' |
| 2 | import { PATTERN_METADATA, TRANSPORT_METADATA } from '@nestjs/microservices/constants' |
| 3 | import { Transport } from '@nestjs/microservices/enums/transport.enum' |
| 4 | |
| 5 | export function setupNatsPattern( |
| 6 | container: ModulesContainer, |
| 7 | metadataScanner: MetadataScanner, |
| 8 | prefix?: string, |
| 9 | ) { |
| 10 | if (!prefix) { |
| 11 | return |
| 12 | } |
| 13 | |
| 14 | for (const module of container.values()) { |
| 15 | for (const controller of module.controllers.values()) { |
| 16 | const instance = controller.instance |
| 17 | if (!instance) |
| 18 | continue |
| 19 | |
| 20 | const instancePrototype = Object.getPrototypeOf(instance) |
| 21 | const methodNames = metadataScanner.getAllMethodNames(instancePrototype) |
| 22 | |
| 23 | for (const methodName of methodNames) { |
| 24 | const method = instancePrototype[methodName] |
| 25 | if (!method) |
| 26 | continue |
| 27 | |
| 28 | const patterns = Reflect.getMetadata(PATTERN_METADATA, method) |
| 29 | const transport = Reflect.getMetadata(TRANSPORT_METADATA, method) |
| 30 | |
| 31 | if ( |
| 32 | patterns |
| 33 | && Array.isArray(patterns) |
| 34 | && transport === Transport.NATS |
| 35 | ) { |
| 36 | const prefixedPatterns = patterns.map((pattern) => { |
| 37 | if (typeof pattern === 'string') { |
| 38 | return `${prefix}.${pattern}` |
| 39 | } |
| 40 | return pattern |
| 41 | }) |
| 42 | |
| 43 | Reflect.defineMetadata(PATTERN_METADATA, prefixedPatterns, method) |
| 44 | } |
| 45 | } |
| 46 | } |
| 47 | } |
| 48 | } |
| 49 |