Skip to content

Commit 0578758

Browse files
committed
docs(env): Improved documentation of EnvModuleMixin
1 parent 7b30873 commit 0578758

File tree

3 files changed

+48
-23
lines changed

3 files changed

+48
-23
lines changed

apps/nest/src/env/env.definition.ts

-20
This file was deleted.

apps/nest/src/env/env.module.ts

+20-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,21 @@
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';
33

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) {}

packages/nest-utils/src/env/env.module-mixin.ts

+28
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,34 @@ import { plainToInstance } from 'class-transformer';
33
import { validateSync } from 'class-validator';
44
import { config } from 'dotenv';
55

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+
*/
634
export function EnvModuleMixin<TEnv extends object>(env: new (...args: unknown[]) => TEnv) {
735
@Module({})
836
class EnvModule {

0 commit comments

Comments
 (0)