Skip to content

Commit 51bf420

Browse files
committed
feat: add conditional imports
1 parent 33222b3 commit 51bf420

File tree

1 file changed

+29
-4
lines changed

1 file changed

+29
-4
lines changed

src/core/app/app.module.ts

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1+
import { isObjectLike } from '@douglasneuroinformatics/libjs';
12
import { Inject } from '@nestjs/common';
2-
import type { DynamicModule, MiddlewareConsumer, ModuleMetadata, NestModule, Provider } from '@nestjs/common';
3+
import type { DynamicModule, MiddlewareConsumer, NestModule, Provider, Type } from '@nestjs/common';
34
import { APP_FILTER, APP_GUARD, APP_PIPE } from '@nestjs/core';
45
import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler';
6+
import type { ConditionalKeys } from 'type-fest';
57

68
import { GlobalExceptionFilter } from '../filters/global-exception.filter.js';
79
import { delay } from '../middleware/delay.middleware.js';
@@ -15,15 +17,26 @@ import { ValidationPipe } from '../pipes/validation.pipe.js';
1517
import type { RuntimeEnv } from '../../config/schema.js';
1618
import type { PrismaModuleOptions } from '../modules/prisma/prisma.config.js';
1719

18-
export type ImportedModule = NonNullable<ModuleMetadata['imports']>[number];
20+
type ImportedModule = DynamicModule | Type<any>;
21+
22+
type ConditionalImport = {
23+
module: ImportedModule;
24+
when: ConditionalKeys<RuntimeEnv, boolean | undefined>;
25+
};
26+
27+
const isConditionalImport = (value: { [key: string]: any }): value is ConditionalImport => {
28+
return isObjectLike(value.module) && typeof value.when === 'string';
29+
};
30+
31+
type Import = ConditionalImport | ImportedModule;
1932

2033
export type DynamicAppModule = DynamicModule & {
2134
module: typeof AppModule;
2235
};
2336

2437
export type CreateAppModuleOptions = {
2538
envConfig: RuntimeEnv;
26-
imports?: ImportedModule[];
39+
imports?: Import[];
2740
prisma: PrismaModuleOptions;
2841
providers?: Provider[];
2942
};
@@ -77,7 +90,19 @@ export class AppModule implements NestModule {
7790
}
7891

7992
return {
80-
imports: [...coreImports, ...imports],
93+
imports: [
94+
...coreImports,
95+
...imports
96+
.map((value) => {
97+
if (!isConditionalImport(value)) {
98+
return value;
99+
} else if (envConfig[value.when]) {
100+
return value.module;
101+
}
102+
return null;
103+
})
104+
.filter((value) => value !== null)
105+
],
81106
module: AppModule,
82107
providers: [...coreProviders, ...providers]
83108
};

0 commit comments

Comments
 (0)