Skip to content

Instantly share code, notes, and snippets.

@mark05e
Created July 28, 2023 00:19
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 mark05e/73b024e6f1c5373a12b65b8dd689bec3 to your computer and use it in GitHub Desktop.
Save mark05e/73b024e6f1c5373a12b65b8dd689bec3 to your computer and use it in GitHub Desktop.
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&param2=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
}
@mark05e
Copy link
Author

mark05e commented Jul 28, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment