I’ve defined validation schema via Joi with nested object in AWS value:
JavaScript
x
13
13
1
const schema = Joi.object({
2
NODE_ENV: Joi.string()
3
.valid('development', 'production', 'test')
4
.default('development'),
5
PORT: Joi.number().default(3000),
6
AWS: Joi.object({
7
accessKeyId: Joi.string().required(),
8
secretAccessKey: Joi.string().required(),
9
region: Joi.string().required(),
10
bucket: Joi.string().required(),
11
}).required(),
12
});
13
Then I put my schema to config module
JavaScript
1
20
20
1
@Module({
2
imports: [
3
ConfigModule.forRoot({
4
isGlobal: true,
5
validationSchema: schema,
6
validationOptions: {
7
abortEarly: false,
8
cache: false,
9
},
10
}),
11
FilesModule,
12
UsersModule,
13
PostsModule,
14
SharedModule,
15
],
16
controllers: [AppController],
17
providers: [AppService],
18
})
19
export class AppModule {}
20
I’ve added inside .env
file the next value for AWS variable:
JavaScript
1
2
1
AWS={"region": "string", "accessKeyId":"string", "secretAccessKey": "string", "bucket": "string"}
2
but I got the next error message after starting nest:
JavaScript
1
9
1
> project-8v@0.0.1 start /Volumes/MacDATA/NestJs/project-8v
2
> nest start
3
4
5
/Volumes/MacDATA/Lern/NestJs/project-8v/node_modules/@nestjs/config/dist/config.module.js:66
6
throw new Error(`Config validation error: ${error.message}`);
7
^
8
Error: Config validation error: "AWS" must be of type object
9
typeof process.env.AWS
returns a string and Joi doesn’t understand that he should parse it, maybe I need to add some in validationOptions or I miss something. How can I solve it?
Advertisement
Answer
As of Joi v16.0.0, object and array string coercion is no longer available as a built-in option.
You can replicate this functionality by extending Joi. For example:
JavaScript
1
22
22
1
const JoiCustom = Joi.extend({
2
type: 'object',
3
base: Joi.object(),
4
coerce: {
5
from: 'string',
6
method(value) {
7
if (value[0] !== '{' && !/^s*{/.test(value)) {
8
return {
9
value
10
};
11
}
12
try {
13
return { value: JSON.parse(value) };
14
} catch (error) {
15
return {
16
errors: [error]
17
};
18
}
19
}
20
}
21
});
22
Then use JoiCustom
in your schema:
JavaScript
1
7
1
const schema = Joi.object({
2
3
AWS: JoiCustom.object({
4
5
}).required()
6
});
7