Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add split method to Joi.array() #3050

Open
leandroluk opened this issue Oct 4, 2024 · 0 comments
Open

Add split method to Joi.array() #3050

leandroluk opened this issue Oct 4, 2024 · 0 comments
Labels
feature New functionality or improvement

Comments

@leandroluk
Copy link

leandroluk commented Oct 4, 2024

Runtime

node.js

Runtime version

20.17.0

Module version

17.13.3

Used with

@nestjs/config

Any other relevant information

No response

What problem are you trying to solve?

Today I need to pass a list of uri's in a environment variable like this:

NATS_URL = "nats://localhost:4222,nats://localhost:4223,nats://localhost:4224"

Today the only way to slice the variable and validate each element is using a custom validatior inner a Joi.string() method like this:

import {Module} from '@nestjs/common';
import {ConfigModule} from '@nestjs/config';
import Joi from 'joi';

@Module({
  imports: [
    ConfigModule.forRoot({
      validationSchema: Joi.object({
        CACHE_URL: Joi.string()
          .default('nats://localhost:4222')
          .custom((value, helpers) => {
            const uris = value.split(',').map((uri: string) => uri.trim());
            for (const uri of uris) {
              const {error} = Joi.string().uri().validate(uri);
              if (error) return helpers.error('any.invalid');
            }
            return uris;
          })
          .messages({'any.invalid': "Each URI in CACHE_URL must be a valid list of URI's"});
      }),
    }),
  ],
})
export class CacheModule {}

Do you have a new or modified API suggestion to solve the problem?

Maybe create a method .convert() to transform the current validation value and state into another Joi schema validation pipeline, like this:

const schema = Joi.any()
  .custom(value => value.split(','))
  .convert(Joi.array().items(Joi.string().uri()));
@leandroluk leandroluk added the feature New functionality or improvement label Oct 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature New functionality or improvement
Projects
None yet
Development

No branches or pull requests

1 participant