hapijs / joi

The most powerful data validation library for JS
Other
20.95k stars 1.51k forks source link

Reuse Schema - Copy Schema and rename Props Name Recursive #2955

Open michelsampil opened 1 year ago

michelsampil commented 1 year ago

Support plan

Context

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.