Last active
January 25, 2016 20:18
-
-
Save Tin/34cfae637a1414c33445 to your computer and use it in GitHub Desktop.
hapi plugin to handle custom string array query param format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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¶m=value2` which is more standard! | |
// hapi.js supports param=value1¶m=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