Last active
October 13, 2018 12:19
-
-
Save alexmon/574623b0ea6b23e31287d1138fb44b31 to your computer and use it in GitHub Desktop.
create URL string with query parameters in Node (TypeScript)
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
| /** | |
| * | |
| * @param {string} host | |
| * @param {string} path | |
| * @param {Array<[string, string]>} paramList | |
| * @returns {string} | |
| */ | |
| function createStringifiedURI(host: string, path: string, paramList: Array<[string, string]>): string { | |
| const uri = new URL( | |
| path, | |
| host | |
| ); | |
| const queryParamList = new URLSearchParams(); | |
| for (const paramItem of paramList) { | |
| queryParamList.append( | |
| paramItem[0], | |
| paramItem[1] | |
| ); | |
| } | |
| uri.search = Array.from<[string, string], string>( | |
| queryParamList.entries(), | |
| (queryParamItem: [string, string]) => { | |
| return `${encodeURIComponent(queryParamItem[0])}=${encodeURIComponent(queryParamItem[1])}`; | |
| } | |
| ) | |
| .join('&'); | |
| return uri.toString(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment