Home > Software design >  Joi getting validationSchema: Joi.object() error
Joi getting validationSchema: Joi.object() error

Time:07-28

After installing joi on nestjs framework i'm trying to validate two property by joi something like:

import Joi from 'joi';
...
ConfigModule.forRoot({
    isGlobal: true,
    validationSchema: Joi.object(
        {
            PORT: Joi.number().required(),
            MONGODB_URI: Joi.string().required(),
        }
    )
}),
...

but i get this error:

Cannot read properties of undefined (reading 'object')

main.ts:

async function bootstrap() {
    const app = await NestFactory.create(AppModule);
    // @ts-ignore
    app.useGlobalFilters(new ValidationPipe());
    const configService = app.get(ConfigService);
    const port = configService.get<string>('PORT');
    await app.listen(port);
}

full error:

D:\develop\api\src\app.module.ts:16
            validationSchema: Joi.object(
                                  ^
TypeError: Cannot read properties of undefined (reading 'object')
    at Object.<anonymous> (D:\develop\api\src\app.module.ts:16:35)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (D:\develop\api\src\main.ts:2:1)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
PS D:\develop\api>

CodePudding user response:

Either use import * as Joi from 'joi' or set esModuleInterop: true in your tsconfig.json. Joi doesn't use a default export by default, so either a named/namespace import needs to be used (first option) or you need to tell Typescript to treat default and named imports similarly (second option)

  • Related