/**
* Replaces values in API endpoint URLs for prototyping.
*
* @param {string} endpoint The original API endpoint URL.
* @param {object} replacements An object where keys are placeholders and values are the replacements.
* @returns {string} The modified API endpoint URL with placeholders replaced.
*/
function replaceApiEndpoints(endpoint, replacements) {
if (typeof endpoint !== 'string') {
return endpoint; // Return as is if not a string
}
let url = endpoint;
for (const key in replacements) {
if (replacements.hasOwnProperty(key)) {
const placeholder = key;
const replacement = replacements[key];
// Use a regular expression to replace the placeholder
const regex = new RegExp(`\\${placeholder}\\b`, 'g'); //Match whole words
url = url.replace(regex, replacement);
}
}
return url;
}
// Example Usage (can be removed for just the function)
// const originalEndpoint = "/api/users/:id";
// const replacements = { id: 123 };
// const modifiedEndpoint = replaceApiEndpoints(originalEndpoint, replacements);
// console.log(modifiedEndpoint); // Output: /api/users/123
Add your comment