Skip to content

Commit 6bb2c0b

Browse files
committed
Fix GlobalHttpHooks being registered twice when class is provided multiple times
When providing the same service multiple times with `useExisting`, then discovered method would be listed twice.
1 parent 78459b6 commit 6bb2c0b

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { DiscoveredMethodWithMeta } from '@golevelup/nestjs-discovery';
2+
3+
export const uniqueDiscoveredMethods = <T>(
4+
methods: Array<DiscoveredMethodWithMeta<T>>,
5+
) => {
6+
const seenClasses = new Map<object, Map<string, Set<unknown>>>();
7+
const uniqueMethods = [] as typeof methods;
8+
for (const method of methods) {
9+
const clsInstance = method.discoveredMethod.parentClass.instance;
10+
const methodName = method.discoveredMethod.methodName;
11+
if (!seenClasses.has(clsInstance)) {
12+
seenClasses.set(clsInstance, new Map());
13+
}
14+
const seenMethods = seenClasses.get(clsInstance)!;
15+
if (!seenMethods.has(methodName)) {
16+
seenMethods.set(methodName, new Set());
17+
}
18+
const seenMetadata = seenMethods.get(methodName)!;
19+
if (!seenMetadata.has(method.meta)) {
20+
seenMetadata.add(method.meta);
21+
uniqueMethods.push(method);
22+
}
23+
}
24+
return uniqueMethods;
25+
};

src/core/http/http.adapter.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
import type { FastifyInstance, HTTPMethods, RouteOptions } from 'fastify';
1616
import rawBody from 'fastify-raw-body';
1717
import * as zlib from 'node:zlib';
18+
import { uniqueDiscoveredMethods } from '~/common/discovery-unique-methods';
1819
import { ConfigService } from '~/core/config/config.service';
1920
import {
2021
GlobalHttpHook,
@@ -73,7 +74,7 @@ export class HttpAdapter extends PatchedFastifyAdapter {
7374
.get(DiscoveryService)
7475
.providerMethodsWithMetaAtKey<keyof HttpHooks>(GlobalHttpHook.KEY);
7576
const fastify = app.getHttpAdapter().getInstance();
76-
for (const globalHook of globalHooks) {
77+
for (const globalHook of uniqueDiscoveredMethods(globalHooks)) {
7778
const handler = globalHook.discoveredMethod.handler.bind(
7879
globalHook.discoveredMethod.parentClass.instance,
7980
);

0 commit comments

Comments
 (0)