hapijs / joi

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

RangeError: Maximum call stack size exceeded - when using Joi.alternatives().try() inside alter() #2930

Closed BrandonNoad closed 1 year ago

BrandonNoad commented 1 year ago

Support plan

Context

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

I want to tailor an existing schema to allow it or an alternative schema.

Schema:

Joi.object({
    key: Joi.string()
})
    .alter({
        patch: (schema) => Joi.alternatives().try(schema, Joi.object({ state: Joi.string().required() }))
    })
    .tailor('patch')

Data to Validate:

{ state: 'inactive' }

What was the result you got?

RangeError: Maximum call stack size exceeded

What result did you expect?

Validation Passed ({ state: 'inactive' })

Cursor_and_joi_dev_-_Schema_Tester_v17_8_3

Marsup commented 1 year ago

Tailored schemas are done deeply, so the problem with this is that you have created your own infinite loop that you need to break out of.

Something like this should work:

Joi.object({
  key: Joi.string(),
})
  .alter({
    patch: (schema) =>
      schema.$_getFlag("altered")
        ? schema
        : Joi.alternatives().try(
            schema.$_setFlag("altered", true),
            Joi.object({ state: Joi.string().required() })
          ),
  })
  .tailor("patch");
BrandonNoad commented 1 year ago

@Marsup Thanks for the quick response. Your solution resolves the error 🎉 .