hapijs / hapijs/joi

Add split method to Joi.array()

Open
#3,050 0 comments 0 reactions 0 assignees View on GitHub
feature
Dominant language
JavaScript
Stars
21.2k
Forks
1.5k
Avg merge
4h 57m
Merged PRs (30d)
14

Description

### 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:

```ts
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:

```ts
const schema = Joi.any()
.custom(value => value.split(','))
.convert(Joi.array().items(Joi.string().uri()));
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.