Skip to content

Instantly share code, notes, and snippets.

@Tin
Last active January 25, 2016 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tin/34cfae637a1414c33445 to your computer and use it in GitHub Desktop.
Save Tin/34cfae637a1414c33445 to your computer and use it in GitHub Desktop.
hapi plugin to handle custom string array query param format
var Url = require('url');
// This ext add support of string-array value in query param
// syntax is `?param=[value1, value2]` which return `{ param: ['value1', 'value2'] }`
// It turns out that we don't need this at all. Because even hapi.js 8.x support `param=value1&param=value2` which is more standard!
// hapi.js supports param=value1&param=value2
server.ext({
type: 'onRequest',
method: function(request, reply) {
var url = Url.parse(request.url, true);
var ArrayLikeValue = /^\[[^\]]+\]$/;
var hasCutomArrayLikeValue = false;
if(url.query) {
for(paramName in url.query) {
if (url.query.hasOwnProperty(paramName) && ArrayLikeValue.test(url.query[paramName])) {
var values = url.query[paramName].slice(1, -1).split(',');
url.query[paramName] = values;
hasCutomArrayLikeValue = true;
}
}
if(hasCustomeArrayLikeValue) {
request.setUrl(Url.format(url));
}
}
return reply.continue();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment