Skip to content

Instantly share code, notes, and snippets.

@AntonisFK
Created February 28, 2020 17:00
Show Gist options
  • Save AntonisFK/52c3606102ca19a4ce49a66a2eae63d6 to your computer and use it in GitHub Desktop.
Save AntonisFK/52c3606102ca19a4ce49a66a2eae63d6 to your computer and use it in GitHub Desktop.
override request get/set query method to allow comma notation in query params
import merge from 'merge-descriptors';
import qs from 'qs';
import Application from 'koa';
// eslint-disable-next-line func-names
module.exports = function(app: Application) {
merge(app.request, {
get query() {
const str = this.querystring;
if (!str) {
return {};
}
this._querycache = this._querycache || {};
const cache = this._querycache;
let query = cache[str];
if (!query) {
query = qs.parse(str, { comma: true });
// optional delete if not needed
Object.keys(query).forEach(key => {
if (query[key] instanceof String) {
query[key] = query[key].trim();
}
if (query[key] instanceof Array) {
query[key] = query[key]
.map((param: string) => param.trim())
.filter((param: string) => param !== '');
}
});
cache[str] = query;
}
return query;
},
set query(obj) {
this.querystring = qs.stringify(obj);
},
} as any);
return app;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment