Joi deep nested recursive array of alternative objects validation

冷暖自知 提交于 2021-02-11 18:19:38

问题


I have following json I am trying to validate using @hapi/Joi 16+. It largely works up to 3 levels. But after that it wouldn't validate the alternative files. folder schema get validated fine. I am hoping for optimised solution that would validate deep nested array.

In here ONLY folders suppose to have optional children. Files schema should NOT have children. Hence I am using alternatives.

const data = [{
  id: '1', //UUID
  type: 'folder',
  children: [{
      id: '2', //UUID
      type: 'folder',
      children: []
    },
    {
      id: '3', //UUID
      type: 'file',
    }, {
      id: '4', //UUID
      type: 'folder',
      children: [{
        id: '5', //UUID
        type: 'folder',
        children: [{
          id: '7', //UUID
          type: 'file'
        }, {
          id: '6', //UUID
          type: 'folder',
          children: [{
            id: '7', //UUID
            type: 'file'
          }]
        }]
      }]
    }
  ]
}]

JOI schema

import Joi from '@hapi/joi';

const validTypes = ['file', 'jpg'];
const files = Joi.object({
  id: Joi.number().integer(),
  type: Joi.string()
    .valid(...validTypes)
    .required()
});

const children = Joi.object({
  children: Joi.array()
    .items(Joi.alternatives(Joi.link('#children'), files))
    .optional(),
  type: Joi.string()
}).id('#children');

const fileSystem = Joi.object({
  children: Joi.array().items(children),
  id: Joi.number().integer(),
  type: Joi.string()
    .alphanum()
    .required()
});

export const fileSystemSchema = Joi.array().items(fileSystem);

来源:https://stackoverflow.com/questions/60695894/joi-deep-nested-recursive-array-of-alternative-objects-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!