Created
July 28, 2023 00:19
-
-
Save mark05e/73b024e6f1c5373a12b65b8dd689bec3 to your computer and use it in GitHub Desktop.
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
function urlExtractPathAndQuery(urlObject) { | |
try { | |
// Process the path | |
let pathString = ''; | |
if (urlObject.path && urlObject.path.length > 0) { | |
// Use JSON.parse and JSON.stringify to ensure proper stringification | |
const parsedPath = JSON.parse(JSON.stringify(urlObject.path)); | |
pathString = '/' + parsedPath.join('/'); | |
} | |
try { | |
// Process the query | |
let queryString = ''; | |
const parsedQuery = JSON.parse(JSON.stringify(urlObject.query)); | |
if (Array.isArray(parsedQuery) && parsedQuery.length > 0) { | |
// Use JSON.parse and JSON.stringify to ensure proper stringification | |
const queryArray = parsedQuery.map((param) => `${param.key}=${param.value}`); | |
queryString = '?' + queryArray.join('&'); | |
} | |
// Combine path and query into the final result | |
const finalResult = pathString + queryString; | |
return finalResult; | |
} catch (err) { | |
// If there's an error processing the query, return the path only | |
return pathString; | |
} | |
} catch (err) { | |
// If there's an error processing the path, return an empty string | |
return ''; | |
} | |
} | |
function urlExtractPathAndQuery_test() { | |
// Example usage: | |
const urlObj = { | |
path: ['path', 'to', 'resource'], | |
query: [['param1', 'value1'], ['param2', 'value2']] | |
}; | |
const result = urlExtractPathAndQuery(urlObj); | |
console.log(result); // Output: "/path/to/resource?param1=value1¶m2=value2" | |
} | |
function urlExtractPathAndQuery_test_insidePostman() { | |
// pm.request.url = {"protocol":"https","path":["get","get1","get2"],"host":["postman-echo","com"], | |
// "query":[{"key":"foo1","value":"bar1"},{"key":"foo2","value":"bar2"}],"variable":[]} | |
let result = urlExtractPathAndQuery(pm.request.url) | |
console.log(result) // Output: /get/get1/get2?foo1=bar1&foo2=bar2 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Used to extract a url like https://postman-echo.com/get/get1/get2?foo1=bar1&foo2=bar2 to get
/get/get1/get2?foo1=bar1&foo2=bar2
inside postman Pre-request Script or Tests tab.