Skip to content

Instantly share code, notes, and snippets.

@mikeyjk
Last active February 19, 2022 12:40
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 mikeyjk/dfb860145fb55c8ffd5a716be287dbd7 to your computer and use it in GitHub Desktop.
Save mikeyjk/dfb860145fb55c8ffd5a716be287dbd7 to your computer and use it in GitHub Desktop.
encode ParsedUrlQuery to a query string (I later realised an encode func already exists) (I then later realised I didn't need this at all)
import { ParsedUrlQuery } from 'querystring';
import { isArray } from 'lodash';
// allows params with no val
const buildQueryStringFromParams = (params: ParsedUrlQuery = {}): string =>
Object.keys(params)
.map((p, i) => {
const separator = i ? '&' : '?';
const value = params[p] || '';
return isArray(value)
? value
.map(v => `${separator}${p}` + (v !== '' ? `=${encodeURIComponent(v)}` : ``))
.join('')
: `${separator}${p}` + (value !== '' ? `=${encodeURIComponent(value)}` : ``);
})
.join('');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment