Last active
February 19, 2022 12:40
-
-
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)
This file contains hidden or 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
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