如何将布尔值true / false或字符串'true'/'false'列入白名单

时间:2019-06-11 22:25:50

标签: javascript node.js express busboy

是否可以在expressjs中将属性值列入白名单? IE我想将属性值限制为布尔值true / false或字符串'true'/'false'。

因为真相让JS糟透了,我不能这样做

  var foo = Boolean(req.param('foo'));

由于字符串'false'的计算结果为true。

希望简化此操作,但同时也想知道我是否错过了expressjs或multer / busboy中内置的东西:

var fooParam = req.param('foo');
var foo;
if (fooParam === 'true' || fooParam === 'false') {
  foo = fooParam === 'true;
} else if (fooParam === true || fooParam === false) {
  foo = fooParam;
}

3 个答案:

答案 0 :(得分:0)

尝试一下:

let maChaine = true;
let monBooleen = JSON.parse(maChaine); 
console.log(monBooleen); //monBoolen vaut true

maChaine = 'true';
monBooleen = JSON.parse(maChaine); 
console.log(monBooleen); //monBoolen vaut true

maChaine = false;
monBooleen = JSON.parse(maChaine); 
console.log(monBooleen); //monBoolen vaut false

maChaine = 'false';
monBooleen = JSON.parse(maChaine); 
console.log(monBooleen); //monBoolen vaut false

因此,您的代码将是:

var fooParam = req.param('foo');
let foo = [true, false, 'true', 'false'].includes(fooParam)?JSON.parse(fooParam):undefined

答案 1 :(得分:0)

我喜欢这种表示法:

[true, false, 'true', 'false'].includes(req.param('foo'))

它提供了很好的扩展性。

let result: boolean | undefined = undefined;
if ([false, 'false'].includes(req.param('foo'))) {
  result = false;
} else if ([true, 'true'].includes(req.param('foo'))) {
  result = true;
}

答案 2 :(得分:0)

我建议朝相反的方向进行处理-字符串化提供的值并检查结果字符串:

var fooParam = req.param('foo');
// map the string value of each boolean to the corresponding boolean value
var boolMap = new Map([['true', true], ['false', false]]); 
// stringify the provided param (true\'true' => 'true', false\'false' => 'false') 
// and get the corresponding value from the mapping. 
// in case of value that is not true\'true'\false\'false' was provided, undefined will be assigned to foo.
var foo = boolMap.get(String(fooParam));