gpt4 book ai didi

node.js - 添加条件 Joi 架构

转载 作者:太空宇宙 更新时间:2023-11-03 22:42:07 25 4
gpt4 key购买 nike

好吧我放弃了...

如何使 selectorSettings 仅在 selectorStrategy 设置为 tournament 时显示?

selectorStrategy: joi.string().valid(['tournament',  'roulette']).default('tournament'),
selectorSettings: joi.any().when('selectorStrategy', {
is: 'tournament',
then: joi.object().keys({
tournamentSize: joi.number().integer().default(2),
baseWeight: joi.number().integer().default(1)
})
})

我在选项中设置了stripUnknown: true。我的期望是,如果我通过:

 selectorStrategy: 'roulette',
selectorSettings: { tournamentSize: 3 }

我会得到:

selectorStrategy: 'roulette'

如果我这样做:

selectorStrategy: 'tournament'

我会得到:

 selectorStrategy: 'tournament',
selectorSettings: { tournamentSize: 2, baseWeight: 1 }

最佳答案

您需要设置 selectorSettings 默认值,并根据 selectorStrategy 的值有条件地将其删除。

让我们来看看您的两个用例。

根据同级值删除键

const thing = {
selectorStrategy: 'roulette',
selectorSettings: { tournamentSize: 3 },
};

joi.validate(thing, schema, { stripUnknown: true} );

selectorSettings 不会被 stripUnknown 选项删除,因为该 key 不是未知的 - 它位于您的架构中。

我们需要根据 selectorStrategy 的值显式地将其删除:

.when('selectorStrategy', {
is: 'tournament',
otherwise: joi.strip(),
}),

根据兄弟值添加/验证键

const thing = { 
selectorStrategy: 'tournament'
};

joi.validate(thing, schema);

代码并未为 selectorSettings 键本身设置默认值,仅设置其属性。由于不需要 selectorSettings,因此验证通过。

我们需要设置默认值:

selectorSettings: joi
.object()
.default({ tournamentSize: 2, baseWeight: 1 })
<小时/>

处理这两种情况的修改后的代码如下所示:

const joi = require('joi');

const schema = {
selectorStrategy: joi
.string()
.valid(['tournament', 'roulette'])
.default('tournament'),
selectorSettings: joi
.object()
.default({ tournamentSize: 2, baseWeight: 1 })
.keys({
tournamentSize: joi
.number()
.integer()
.default(2),
baseWeight: joi
.number()
.integer()
.default(1),
})
.when('selectorStrategy', {
is: 'tournament',
otherwise: joi.strip(),
}),
};

示例

// should remove settings when not a tournament
var thing = {
selectorStrategy: 'roulette',
selectorSettings: { tournamentSize: 3 },
};

// returns
{
"selectorStrategy": "roulette"
}

.

// should insert default settings
var thing = {
selectorStrategy: 'tournament'
};

// returns
{
"selectorStrategy": "tournament",
"selectorSettings": {
"tournamentSize": 2,
"baseWeight": 1
}
}

.

// should add missing baseWeight default
var thing = {
selectorStrategy: 'tournament',
selectorSettings: { tournamentSize: 5 }
};

// returns
{
"selectorStrategy": "tournament",
"selectorSettings": {
"tournamentSize": 5,
"baseWeight": 1
}
}

关于node.js - 添加条件 Joi 架构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48023850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com