hapijs / hapijs/joi

Unexpected behaviour while making use of fork() and id()

Open
#2,736 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
21.2k
Forks
1.5k
Avg merge
4h 57m
Merged PRs (30d)
14

Description

#### Context

* *node version*: 16.13.2
* *module version with issue*: 17.6.0
* *last module version without issue*: n/a
* *environment* (e.g. node, browser, native): node
* *used with* (e.g. hapi application, another framework, standalone, ...): standalone
* *any other relevant information*: n/a

#### What are you trying to achieve or the steps to reproduce?

While using `any.fork(paths, adjuster)` on an object schema I was expecting to be able to use the key name to adjust the key schema.
Even if the schema of the key had an id assigned to it by `any.id(id)`.

Minimal example:
```js
const schema = Joi.object({
myField: Joi.string().id('myId'),
})
.fork('myField', keySchema => keySchema.required());

// Expecting `myField` to be marked as required, resulting in an error here, but validation passes.
schema.validate({});
// -> { value: {} }
```
Replacing `myField` with `myId` does work. That was however not what I was expecting. It seemed logical to me that fork is being applied to the object schema and therefore being able to supply the key by its name, not the id of the key schema.

More elaborate example closer to the actual use case:
```js
// Schema definition of a recursive object. Reused in multiple other schemas.
const recursiveObjectSchema = Joi.object({
/* complex properties with references back to this object using `Joi.link('#myId')` */
})
.id('myId');

// A base schema for one of the models using the recursive object. Extended and forked in other places.
const baseSchema = Joi.object({
myField: recursiveObjectSchema,
});

// Creating a more strict schema by forking the base.
const requiredKeys = ['myField'];
// Expecting to be able to use the key mentioned in the baseSchema here, not the id set in recursive schema definition 2 levels up.
const strictSchema = baseSchema.fork(requiredKeys, keySchema => keySchema.required());

const emptyObject = {};

// Expecting an error here, but not getting one
strictSchema.validate(emptyObject);
// -> { value: {} }
```

#### What was the result you got?
Not able to use fork on an object to mark a key by its name as required, where the key schema had an id assigned to it.

#### What result did you expect?
As mentioned in the documentation, use `any.fork(paths, adjuster)` to adjust the keys by their name not (just) their id.

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.