6

I am using node.js restify.

I have a HTTP GET request that looks like this;

http://127.0.0.1//read_val?XXX=123&YYY=456&ZZZ=789

In my handling function, to retrieve the URL parameters, the relevant code will be like this;

var api_get_func = function (app, url_path) {
    function respond(req, res, next) {
        var XXX= req.query.XXX;
        var YYY = req.query.YYY;
        var ZZZ = req.query.ZZZ;

        //SQL query ...
        return next();
    }

    app.get(url_path, respond);
} 

Now, what if I have a HTTP GET function like this below

http://127.0.0.1//read_val?XXX=123&YYY=456

The ZZZ parameter is not provided in the URL. How do I modify the code such that ZZZ will use a default value of, say, 111?

guagay_wk
  • 26,337
  • 54
  • 186
  • 295

3 Answers3

8

If just want to check if something is provided, then you could just do:

var ZZZ = req.query.ZZZ || 111;

But... GET parameters are query strings, so we probably want to make sure it is a number.

if (!parseInt(req.query.ZZZ)) {
  req.query.ZZZ = 111;
}

Or if you want to get ternary with it:

req.query.ZZZ = parseInt(req.query.ZZZ) ? req.query.ZZZ : 111;

Do note that the other parameters are a string and that this default is being set as a number. So, you might want '111' as opposed to 111. Also, you can parseInt all of your query strings or toString them all if they are all a number, just try to make sure they all remain the same expected type. Unless of course these are all strings of text, in which case ignore all this.

Kevin Reilly
  • 6,096
  • 2
  • 25
  • 18
2
var api_get_func = function (app, url_path) {
    function respond(req, res, next) {
        var XXX= req.query.XXX;
        var YYY = req.query.YYY;
        var ZZZ = req.query.ZZZ || <YOUR DEFAULT VALUE>;

        //SQL query ...
        return next();
    }`enter code here`

    app.get(url_path, respond);
} 
Atul Agrawal
  • 1,474
  • 5
  • 22
  • 41
1

In one line, the best way is this:

let limit = parseInt(req.query.limit || 0);
let page = parseInt(req.query.pagina || 1);
let offset = page * limit

Because you put a default value then you parse the content.

req.query.limit || 0

This line check if the content was sent, if not, put 0 as default value

Mike Brian Olivera
  • 1,414
  • 1
  • 16
  • 21
  • Beware that parseInt might return NaN values if the req.query.limit is "abc" as example. –  Jun 16 '20 at 06:55