Reuse Schema - Copy Schema and rename Props Name Recursive
- Dominant language
- JavaScript
- Stars
- 21.2k
- Forks
- 1.5k
- Avg merge
- 4h 57m
- Merged PRs (30d)
- 14
Description
#### Support plan
* *is this issue currently blocking your project?* (yes/no): yes
* *is this issue affecting a production system?* (yes/no): no
#### Context
* *node version*: 18.15.0
* *module version*: 17.6.0
* *environment* (e.g. node, browser, native): node
* *used with* (e.g. hapi application, another framework, standalone, ...): standalone
* *any other relevant information*:
#### What problem are you trying to solve?
Reuse an Joi object schema. I'm trying to copy a schema and rename props name recursive.
.rename() method and a patter for renaming only works for the first props level, not recursive. so nested object props aren't renamed.
```
const schema = Joi.object({
first_name: Joi.string().required(),
address_number: Joi.number(),
user_inventory: {
user_armour: Joi.string(),
user_weapon: Joi.string(),
user_spells: [Joi.array().items(Joi.object())]
}
});
const input = {
firstName: 'Mr. 🥑',
addressNumber: 555523123,
userInventory: {
userArmor: '🥑',
userWeapon: '🍗',
userSpells: [{ firstSpell: 'abc' }, { secondSpell: 'second spell' }]
}
};
let newSchema = schema.rename(
/([^\s]+)/,
Joi.expression('{#1}', {
adjust: (value) => translatePropName(value.toString())
})
);
```
#### Do you have a new or modified API suggestion to solve the problem?
I think there are many approaches to solve the problem
1 - The hardest one, but the full solution is a function to copy an schema and rename the specified props with the new property name. some like:
```
const = [ {name: 'renameName'}, {age: 'renamedAge' }, {inventory: }]
const schema = Joi.object({
first_name: Joi.string().required(),
address_number: Joi.number()
})
//perfect solution something like...
const newPropsNameMap = [{fist_name: 'new_fist_name', address_number: 'new_address_number'}]
const newSchema = schema.copy().rename(newPropsNameMap)
// OR
const newSchema = schema.copy().rename((e)=>{renamingFunction(e)})
```
2 - Let multiple rename() method execution on a schema and let rename nested properties (isn't possible to access nowadays). isn't possible to do multiple attributes renames. the only option for multiple renames is to have a regex and rename the matching groups. the rename() method only accept a string or a regex in order to change a property name, sadly we the regex isn't applied to nested object properties. so another solution should let to do multiple renames on a schema (included nested schemas) or let rename nested objet properties so I can call a function to rename it recursive.
Contributor guide
Assessment
This issue has not been assessed yet.