Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to parse Boolean query string param in node/express

I'm waiting for something like the following from the front end

....?isUpdated=true

so I did something like this in code (as I'm processing only isUpdated=true, false need to be ignored)

var isUpdated = (req.query.isUpdated === 'true')

but it seems bit odd to me.

How to do this in proper way? I mean to parse a Boolean parameter from the query string.

like image 793
Jesus_Maria Avatar asked Sep 20 '16 16:09

Jesus_Maria


4 Answers

Docs if you are using query-string

const queryString = require('query-string');

queryString.parse('foo=true', {parseBooleans: true});
//=> {foo: true}
like image 165
Tawfik Nasser Avatar answered Nov 14 '22 22:11

Tawfik Nasser


The only thing I would change about your approach is to make it case insensitive:

var isUpdated = ((req.query.isUpdated+'').toLowerCase() === 'true')

You could make this a utility function as well if you like:

function queryParamToBool(value) {
  return ((value+'').toLowerCase() === 'true')
}
var isUpdated = queryParamToBool(req.query.isUpdated)
like image 4
Kyle Falconer Avatar answered Nov 14 '22 20:11

Kyle Falconer


I use this pair of lines:

let test = (value).toString().trim().toLowerCase(); let result = !((test === 'false') || (test === '0') || (test === ''));

like image 3
Guillermojortizr Avatar answered Nov 14 '22 22:11

Guillermojortizr


Here is my generic solution for getting a query params as a boolean:

const isTrue = Boolean((req.query.myParam || "").replace(/\s*(false|null|undefined|0)\s*/i, ""))

It converts the query param into a string which is then cleaned by suppressing any falsy string. Any resulting non-empty string will be true.

like image 2
ncenerar Avatar answered Nov 14 '22 21:11

ncenerar