periphery
periphery

Reputation: 75

How do I enforce a check for a particular sequence of parameters in the querystring of an http request handled by a node.js server?

From node.js documentation

querystring.parse('foo=bar&baz=qux&baz=quux&corge')

// returns
{ foo: 'bar', baz: ['qux', 'quux'], corge: '' }

When I parse for the parameters on the server side, is there a way I can check if these parameters are sent in a correct sequence?

For example, I want to enforce that the foo=bar is always the FIRST parameter and so on. How is this achievable?

Right now I can do something like:

var queryData = querystring.parse('foo=bar&baz=qux&baz=quux&corge');

But then doing

if(queryData.foo) {...}

only checks if the parameter 'foo' is present in the url, not if it's in the right place

Upvotes: 0

Views: 112

Answers (3)

azero0
azero0

Reputation: 2310

check if this code works for you:

var querystring = require("querystring");
var obj =  querystring.parse('foo=bar&baz=qux&baz=quux&corge');

var rankOfObjects = {"0":"foo","1":"baz","2":"corge"};
var objArray = Object.keys(obj);

if(checkRank()){
    console.log("in order");
}else{
    console.log("not in order");
}

function checkRank(){
    for(var rank in objArray){
        if(objArray[rank]!=rankOfObjects[rank]){
             return false;
        }
     }
     return true
}

Upvotes: 0

Farid Nouri Neshat
Farid Nouri Neshat

Reputation: 30410

You can either parse it yourself with something like this:

var qs = 'foo=bar&baz=qux&baz=quux&corge';
var parsed = qs.split('&').map(function (keyValue) {
    return keyValue.split('=');
});

Which will give you something like [ ['foo','bar'], ['baz', 'qux'], ['baz', 'quux'], ['corge', '' ], then you can check if the first is what you want or not: if (parsed[0][0] === 'foo')

You can also check this question for parsing it yourself: How can I get query string values in JavaScript?

Or you can rely on the fact that nodejs will insert the property in the same order it was received and v8 will keep the order(which is not really reliable, they might change the behavior): if (Object.keys(queryData)[0] === 'foo').

Or you can just check if foo is appeared first:

if (qs.indexOf('foo=') === 0)

or something like if (qs.slice(0, 4) === 'foo')

Upvotes: 3

TGH
TGH

Reputation: 39248

You might be better of doing an old fashion string.split since it gives you an array of split elements. You can then inspect the array

How do I split a string, breaking at a particular character?

Upvotes: 0

Related Questions