So, req.query returns the hash of the query parameters. Even better, if a parameter is actually a json object, then it parses it into the respective json, which is awesome.
However, how can I customize this parsing? For instance, I would like a certain value to be parsed as a number, rather than as a string. Surely, I can do it post factum and modify the returned object. But, I am interesting to know whether the process can be customized in general.
EDIT
For example, consider the following request:
GET http://localhost:8000/admin/api/inventory?rowsPerPage=25&page=0&q%5Bqty%5D%5B%24lt%5D=100
Decoding it we get:
GET http://localhost:8000/admin/api/inventory?rowsPerPage=25&page=0&q[qty][$lt]=100
Now, express converts these query parameters to
req.query = {rowsPerPage: "25", page: "0", q: {qty: {$lt: "100"}}
My problem is with "25", "0" and "100" - I want them to be numbers. So, I can either change the req.query
post factum or interfere with the parsing process. I want to learn the latter.
the query string is parsed here connect-query.js which is based on tj's querystring parser node-querystring you may want to look into that or into nodes querystring parser. AFAIK u cannot change the qs parsing without forking express and changing something in there. anyways handling this cases in a middleware or later on in your app where you need the strings to be numbers would be better performance wise instead of checking for numbers in every request.
You should have a look at the req.query middleware provided by connect. It is based on node-querystring.
This is how I do it (using CoffeeScript and Lodash):
app.use (req, res, next) ->
# Ensure all integer parameters are parsed correctly.
_.each req.query, (value, key) ->
unless isNaN value
req.query[key] = _.parseInt value
next()
The same can easily be achieved with JavaScript and no extensions.