File tree 3 files changed +48
-23
lines changed
packages/nest-utils/src/env
3 files changed +48
-23
lines changed Load Diff This file was deleted.
Original file line number Diff line number Diff line change 1
- import { EnvModuleMixin } from '@spuxx/nest-utils' ;
2
- import { Environment } from './env.definition ' ;
1
+ import { EnvModuleMixin , ApplicationLogLevel } from '@spuxx/nest-utils' ;
2
+ import { IsIn , IsString , IsUrl } from 'class-validator ' ;
3
3
4
- export class EnvModule extends EnvModuleMixin < Environment > ( Environment ) { }
4
+ class Env {
5
+ @IsString ( )
6
+ @IsIn ( Object . values ( ApplicationLogLevel ) )
7
+ APP_LOG_LEVEL : ApplicationLogLevel = ApplicationLogLevel . Default ;
8
+
9
+ @IsString ( )
10
+ APP_BASE_URL : string = 'http://localhost:3000' ;
11
+
12
+ @IsUrl ( )
13
+ AUTH_ISSUER_URL : string = 'https://auth.spuxx.dev/realms/spuxx/' ;
14
+
15
+ @IsString ( )
16
+ AUTH_CLIENT_ID : string = 'test' ;
17
+
18
+ @IsString ( )
19
+ AUTH_CLIENT_SECRET : string ;
20
+ }
21
+ export class EnvModule extends EnvModuleMixin < Env > ( Env ) { }
Original file line number Diff line number Diff line change @@ -3,6 +3,34 @@ import { plainToInstance } from 'class-transformer';
3
3
import { validateSync } from 'class-validator' ;
4
4
import { config } from 'dotenv' ;
5
5
6
+ /**
7
+ * A mixin for a NestJS module that provides easy access to environment variables.
8
+ * The module also handles validation of the environment variables using `class-validator`
9
+ * on start-up.
10
+ * @param env The class that defines the environment variables.
11
+ * @returns The `EnvModule` class.
12
+ * @example
13
+ * // env.module.ts
14
+ * import { IsNumber, IsString } from 'class-validator';
15
+ * class Env {
16
+ * @IsNumber()
17
+ * PORT: number; // Will throw an error if not provided in .env file
18
+ *
19
+ * @IsString()
20
+ * GREETING_ROUTE: string = '/hello'; // Will default to '/hello' if not provided in .env file
21
+ * }
22
+ * export class EnvModule extends EnvModuleMixin<Env>(Env) {}
23
+ *
24
+ * // app.module.ts
25
+ * @Module({
26
+ * imports: [EnvModule],
27
+ * })
28
+ * export class AppModule {}
29
+ *
30
+ * // You can access any environment variable through EnvModule.get()
31
+ * console.log(EnvModule.get('PORT')); // This is type-safe!
32
+ * @Get(EnvModule.get('GREETING_ROUTE')) // Works with decorators!
33
+ */
6
34
export function EnvModuleMixin < TEnv extends object > ( env : new ( ...args : unknown [ ] ) => TEnv ) {
7
35
@Module ( { } )
8
36
class EnvModule {
You can’t perform that action at this time.
0 commit comments