Skip to content

Commit

Permalink
feat(): let ConfigService type know about schema validation
Browse files Browse the repository at this point in the history
Closes #668
  • Loading branch information
micalevisk committed Oct 1, 2021
1 parent a403003 commit f6d4b6b
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
11 changes: 7 additions & 4 deletions lib/config.service.ts
Expand Up @@ -7,7 +7,7 @@ import {
CONFIGURATION_TOKEN,
VALIDATED_ENV_PROPNAME,
} from './config.constants';
import { NoInferType, Path, PathValue } from './types';
import { NoInferType, Path, PathValue, ExcludeUndefinedIf } from './types';

export interface ConfigGetOptions {
/**
Expand All @@ -19,7 +19,10 @@ export interface ConfigGetOptions {
}

@Injectable()
export class ConfigService<K = Record<string, unknown>> {
export class ConfigService<
K = Record<string, unknown>,
WasValidated extends boolean = false,
> {
private set isCacheEnabled(value: boolean) {
this._isCacheEnabled = value;
}
Expand All @@ -42,7 +45,7 @@ export class ConfigService<K = Record<string, unknown>> {
* based on property path (you can use dot notation to traverse nested object, e.g. "database.host").
* @param propertyPath
*/
get<T = any>(propertyPath: keyof K): T | undefined;
get<T = any>(propertyPath: keyof K): ExcludeUndefinedIf<WasValidated, T>;
/**
* Get a configuration value (either custom configuration or process environment variable)
* based on property path (you can use dot notation to traverse nested object, e.g. "database.host").
Expand All @@ -52,7 +55,7 @@ export class ConfigService<K = Record<string, unknown>> {
get<T = K, P extends Path<T> = any, R = PathValue<T, P>>(
propertyPath: P,
options: ConfigGetOptions,
): R | undefined;
): ExcludeUndefinedIf<WasValidated, R>;
/**
* Get a configuration value (either custom configuration or process environment variable)
* based on property path (you can use dot notation to traverse nested object, e.g. "database.host").
Expand Down
10 changes: 10 additions & 0 deletions lib/types/exclude-undefined-if.type.ts
@@ -0,0 +1,10 @@
/**
* `ExcludeUndefinedIf<ExcludeUndefined, T>
*
* If `ExcludeUndefined` is `true`, remove `undefined` from `T`.
* Otherwise, constructs the type `T` with `undefined`.
*/
export type ExcludeUndefinedIf<
ExcludeUndefined extends boolean,
T,
> = ExcludeUndefined extends true ? Exclude<T, undefined> : T | undefined;
1 change: 1 addition & 0 deletions lib/types/index.ts
Expand Up @@ -2,3 +2,4 @@ export * from './config-object.type';
export * from './config.type';
export * from './no-infer.type';
export * from './path-value.type';
export * from './exclude-undefined-if.type';

0 comments on commit f6d4b6b

Please sign in to comment.