3

A correctly formed query string looks like:

http://baseurl.thing/update?id=123&foo=50&bar20

I want to map this "safely" into an object, but I don't want to end up with undefined values. Is there a nice way of validating the query string?

Details: I want to turn this into an object with the url module. i.e.:

var url_parts = url.parse(request.url, true);

and then I can route based on url_parts.pathname. I want to access url_parts.query.id, url_parts.query.foo and url_parts.query.bar, but only if they all exist and only if no other parameters were supplied, so that I don't get silent undefined values appearing.

2
  • 2
    I don't get it. You have the query object already, so why not just do if (query.id && query.foo && query.bar) { ... }? Commented Jan 24, 2011 at 15:51
  • I wanted to check that no other parameters were supplied, ie that it conforms exactly. I guess I can just ignore other parameters if it's a pain. Commented Jan 24, 2011 at 16:43

1 Answer 1

6

set up defaults, and then overwrite them with values from your url.

EXAMPLE

var defaults = {
    id : 0,
    foo : 'default value',
    bar : 'default.value'
};

var url_parts = url.parse(request.url, true);
var query = url_parts.query;
query.prototype = defaults; //does the inheritance of defaults thing
// now query has all values set, even if they didn't get passed in.

Hope that helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.