我正在尝试基于 joi 模式添加空值

问题描述 投票:0回答:0

基本上我有一个 joi 模式,它可能会有所不同,我正在尝试创建一个通用解决方案, 示例:

const templateSchema = Joi.object({
        studentData: Joi.object({
           addr: Joi.object({
               studentName: Joi.string().required(),
               studentAge: Joi.number().required()
           }).required(),
           education: Joi.object({
                schoolName: Joi.string().required(),
                studentGrade: Joi.number().required()
           }).required()
        }).required()
    }).required();

数据示例

const apiData = {
    studentData: {
        addr: null,
        education: {
            schoolName: "TKM",
            studentGrade: 10
        }
    }
};`

`const apiData = {
    studentData: {
        education: {
            schoolName: "TKM",
            studentGrade: 10
        }
    }
};

我正在寻找一个通用的解决方案,它适用于任何复杂的模式和数据,并将 null 添加到末尾叶子的节点

我尝试过的解决方案,但并不适用于所有情况

function populateMissingFields(data, error, schemaDescription) {
    if (error && error.details) {
        error.details.forEach(detail => {
            const currentPathValue = _.get(data, detail.path);

            if (detail.type === 'object.base' && (currentPathValue === null || currentPathValue === undefined)) {
                expandObjectBasedOnSchema(data, detail.path, schemaDescription);
            } else if (detail.type === 'array.base' && !Array.isArray(currentPathValue)) {
                _.set(data, detail.path, []);
            } else {
                _.set(data, detail.path, null);
            }
        });
    }
    return data;
}
function expandObjectBasedOnSchema(data, path, rootSchemaDescription) {
    let currentSchemaDesc = rootSchemaDescription;
    for (const key of path) {
        if (currentSchemaDesc.keys && currentSchemaDesc.keys[key]) {
            currentSchemaDesc = currentSchemaDesc.keys[key];
        } else {
            console.error('Unable to find schema for path:', path);
            return;
        }
    }

    if (currentSchemaDesc.type === 'object') {
        const objectToSet = {};
        for (const [key, keySchema] of Object.entries(currentSchemaDesc.keys || {})) {
            if (keySchema.type === 'object') {
                objectToSet[key] = {};
            } else if (keySchema.type === 'array') {
                objectToSet[key] = []; 
            } else {
                objectToSet[key] = null; 
            }
        }
        _.set(data, path, objectToSet);
    }
}
const validatedResult = templateSchema.validate(apiData, { abortEarly: false });
const modifiedData = populateMissingFields(apiData, validatedResult.error, templateSchema.describe());
console.log(modifiedData)

所以它并不适用于所有情况,如果 sn 对象丢失,它就不起作用,我们需要转到最后一个叶子

预期产出

const apiData = {
    studentData: {
       addr:{
           studentName: null,
           studentAge:null
        }
        education: {
            schoolName: "TKM",
            studentGrade: 10
        }
    }
};
javascript json lodash joi
© www.soinside.com 2019 - 2024. All rights reserved.