7

In the NestJS documentation there is a section about partial registration. It says it allows to load feature-specific configuration files in different directories:

import databaseConfig from './config/database.config';

@Module({
  imports: [ConfigModule.forFeature(databaseConfig)],
})
export class DatabaseModule {}

However, it seems that it is not possible to provide a feature-specific validation schema, as Config is the only argument that you can give to the forFeature method. Am I correct to assume that I would need to provide this database config validation schema in the ConfigModule.forRoot method? This seems to defeat the purpose of a feature specific configuration file as the validation would need to be defined higher up?

Are there other ways to achieve partial registration with validation?

warreee
  • 437
  • 4
  • 12

1 Answers1

2

There is different ways to accomplish validations using the forFeature() method. I admit that they are not so evident and the documentation does not mention an example.

I was in your position before and I didn't know how to do it, that's why I have created an article here with a recap of all the possible ways that I can think of.

I will show you here a quick way in case anyone needs a fast solution and doesn't have time to read my article.

Using Joi

Install the required dependency:

npm install --save joi

Let's create a configuration namespace and apply validations. The databaseConfig that you need will look like this:

import { registerAs } from '@nestjs/config';
import * as Joi from 'joi';

export default registerAs('my-app-config-namespace', () => {
  // Our environment variables
  const values = {
    nodeEnv: process.env.NODE_ENV,
    port: parseInt(process.env.PORT),
  };

  // Joi validations
  const schema = Joi.object({
    nodeEnv: Joi.string().required().valid('development', 'production'),
    port: Joi.number().required(),
  });

  // Validates our values using the schema.
  // Passing a flag to tell Joi to not stop validation on the
  // first error, we want all the errors found.
  const { error } = schema.validate(values, { abortEarly: false });

  // If the validation is invalid, "error" is assigned a
  // ValidationError object providing more information.
  if (error) {
    throw new Error(
      `Validation failed - Is there an environment variable missing?
        ${error.message}`,
    );
  }

  // If the validation is valid, then the "error" will be
  // undefined and this will return successfully.
  return values;
});

I hope it's helpful.

RRGT19
  • 1,437
  • 3
  • 28
  • 54