forked from Nikaple/nest-typed-config
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: support selecting optional configs with selectConfig (Nikaple#82)
- Loading branch information
Showing
5 changed files
with
39 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,16 +1,31 @@ | ||
import { DynamicModule, ValueProvider } from '@nestjs/common'; | ||
import { ClassConstructor } from 'class-transformer'; | ||
|
||
export const selectConfig = <T>( | ||
export interface SelectConfigOptions { | ||
/** | ||
* when true, allow undefined config declared with `@IsOptional()` | ||
*/ | ||
allowOptional?: boolean; | ||
} | ||
|
||
export const selectConfig = <T, Option extends SelectConfigOptions>( | ||
module: DynamicModule, | ||
Config: ClassConstructor<T>, | ||
): T => { | ||
options?: Option, | ||
): Option extends { allowOptional: true } ? T | undefined : T => { | ||
const providers = module.providers as ValueProvider<T>[]; | ||
const selectedConfig = (providers || []).filter( | ||
({ provide }) => provide === Config, | ||
)[0]; | ||
if (options?.allowOptional) { | ||
return selectedConfig?.useValue; | ||
} | ||
if (!selectedConfig) { | ||
throw new Error(`You can only select config which exists in providers`); | ||
throw new Error( | ||
'You can only select config which exists in providers. \ | ||
If the config being selected is marked as optional, \ | ||
please pass `allowOptional` in options argument.', | ||
); | ||
} | ||
return selectedConfig.useValue; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters