nestjs-telegraf/lib/services/base-explorer.service.ts

53 lines
1.5 KiB
TypeScript
Raw Normal View History

2021-01-02 01:27:01 +03:00
import { InstanceWrapper } from '@nestjs/core/injector/instance-wrapper';
import { Module } from '@nestjs/core/injector/module';
2021-01-03 16:11:17 +03:00
import { flattenDeep, identity, isEmpty } from 'lodash';
2021-01-02 01:27:01 +03:00
export class BaseExplorerService {
getModules(
modulesContainer: Map<string, Module>,
include: Function[],
): Module[] {
if (!include || isEmpty(include)) {
return [...modulesContainer.values()];
}
2022-07-09 13:15:13 +03:00
return this.includeWhitelisted(modulesContainer, include);
2021-01-02 01:27:01 +03:00
}
includeWhitelisted(
modulesContainer: Map<string, Module>,
include: Function[],
): Module[] {
const modules = [...modulesContainer.values()];
2021-01-05 00:32:31 +03:00
return modules.filter(({ metatype }) => include.includes(metatype));
2021-01-02 01:27:01 +03:00
}
2021-01-03 16:11:17 +03:00
flatMap<T>(
2021-01-02 01:27:01 +03:00
modules: Module[],
callback: (instance: InstanceWrapper, moduleRef: Module) => T | T[],
): T[] {
2021-02-22 13:20:13 +03:00
const visitedModules = new Set<Module>();
const unwrap = (moduleRef: Module) => {
// protection from circular recursion
if (visitedModules.has(moduleRef)) {
return [];
} else {
visitedModules.add(moduleRef);
}
const providers = [...moduleRef.providers.values()];
const defined = providers.map((wrapper) => callback(wrapper, moduleRef));
const imported: (T | T[])[] = moduleRef.imports?.size
? [...moduleRef.imports.values()].reduce((prev, cur) => {
return [...prev, ...unwrap(cur)];
}, [])
: [];
return [...defined, ...imported];
2021-01-02 01:27:01 +03:00
};
2021-02-22 13:20:13 +03:00
return flattenDeep(modules.map(unwrap)).filter(identity);
2021-01-02 01:27:01 +03:00
}
}