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.
Docs if you are using query-string
const queryString = require('query-string');
queryString.parse('foo=true', {parseBooleans: true});
//=> {foo: true}
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)
I use this pair of lines:
let test = (value).toString().trim().toLowerCase();
let result = !((test === 'false') || (test === '0') || (test === ''));
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With