Skip to content

Commit 1c4c19a

Browse files
docs: add note on validation inside config functions #2291
1 parent c0f35b9 commit 1c4c19a

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

content/techniques/configuration.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,27 @@ export default () => {
161161

162162
> warning **Note** Nest CLI does not automatically move your "assets" (non-TS files) to the `dist` folder during the build process. To make sure that your YAML files are copied, you have to specify this in the `compilerOptions#assets` object in the `nest-cli.json` file. As an example, if the `config` folder is at the same level as the `src` folder, add `compilerOptions#assets` with the value `"assets": [{{ '{' }}"include": "../config/*.yaml", "outDir": "./dist/config"{{ '}' }}]`. Read more [here](/cli/monorepo#assets).
163163

164+
Just a quick note - configuration files aren't automatically validated, even if you're using the `validationSchema` option in NestJS's `ConfigModule`. If you need validation or want to apply any transformations, you'll have to handle that within the factory function where you have complete control over the configuration object. This allows you to implement any custom validation logic as needed.
165+
166+
For example, if you want to ensure that port is within a certain range, you can add a validation step to the factory function:
167+
168+
```typescript
169+
@@filename(config/configuration)
170+
export default () => {
171+
const config = yaml.load(
172+
readFileSync(join(__dirname, YAML_CONFIG_FILENAME), 'utf8'),
173+
) as Record<string, any>;
174+
175+
if (config.http.port < 1024 || config.http.port > 49151) {
176+
throw new Error('HTTP port must be between 1024 and 49151');
177+
}
178+
179+
return config;
180+
};
181+
```
182+
183+
Now, if the port is outside the specified range, the application will throw an error during startup.
184+
164185
<app-banner-devtools></app-banner-devtools>
165186

166187
#### Using the `ConfigService`

0 commit comments

Comments
 (0)