簡體   English   中英

Joi.object().keys() 和 append() 方法在添加更多鍵方面有什么區別

[英]What's the difference between Joi.object().keys() and append() methods in terms of adding more keys

我有這段代碼

const baseSchema = Joi.object.keys({
   name: Joi.string().required()
})

現在我想為這個模式添加更多的鍵,我可以寫

const basicInfoSchema = baseSchema.keys({
   address: Joi.string().required(),
   phoneNumber: Joi.number().required()
})

或者

const basicInfoSchema = baseSchema.append({
   address: Joi.string().required(),
   phoneNumber: Joi.number().required()
})

兩者有什么區別?

append有一個通用參數,可以為預期的 object 提供一些類型。 就像Joi.object<>()一樣。 keys沒有通用參數。

還查看下面的源代碼(版本 17.6.0),您可以看到 append 調用引擎蓋下的keys 我不會粘貼文檔,但您可以在那里閱讀https://joi.dev/api/?v=17.6.0

基本上, append只做keys方法的else子句。 keys也可以“允許所有”(允許任何鍵)或“不允許任何鍵”(不允許任何鍵)現有鍵。 keys有兩個額外的功能。

        append: {
            method(schema) {

                if (schema === null ||
                    schema === undefined ||
                    Object.keys(schema).length === 0) {

                    return this;
                }

                return this.keys(schema);
            }
        },
        keys: {
            method(schema) {

                Assert(schema === undefined || typeof schema === 'object', 'Object schema must be a valid object');
                Assert(!Common.isSchema(schema), 'Object schema cannot be a joi schema');

                const obj = this.clone();

                if (!schema) {                                      // Allow all
                    obj.$_terms.keys = null;
                }
                else if (!Object.keys(schema).length) {             // Allow none
                    obj.$_terms.keys = new internals.Keys();
                }
                else {
                    obj.$_terms.keys = obj.$_terms.keys ? obj.$_terms.keys.filter((child) => !schema.hasOwnProperty(child.key)) : new internals.Keys();
                    for (const key in schema) {
                        Common.tryWithPath(() => obj.$_terms.keys.push({ key, schema: this.$_compile(schema[key]) }), key);
                    }
                }

                return obj.$_mutateRebuild();
            }
        },

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM