1. /**
  2. * Replaces values in API endpoint URLs for prototyping.
  3. *
  4. * @param {string} endpoint The original API endpoint URL.
  5. * @param {object} replacements An object where keys are placeholders and values are the replacements.
  6. * @returns {string} The modified API endpoint URL with placeholders replaced.
  7. */
  8. function replaceApiEndpoints(endpoint, replacements) {
  9. if (typeof endpoint !== 'string') {
  10. return endpoint; // Return as is if not a string
  11. }
  12. let url = endpoint;
  13. for (const key in replacements) {
  14. if (replacements.hasOwnProperty(key)) {
  15. const placeholder = key;
  16. const replacement = replacements[key];
  17. // Use a regular expression to replace the placeholder
  18. const regex = new RegExp(`\\${placeholder}\\b`, 'g'); //Match whole words
  19. url = url.replace(regex, replacement);
  20. }
  21. }
  22. return url;
  23. }
  24. // Example Usage (can be removed for just the function)
  25. // const originalEndpoint = "/api/users/:id";
  26. // const replacements = { id: 123 };
  27. // const modifiedEndpoint = replaceApiEndpoints(originalEndpoint, replacements);
  28. // console.log(modifiedEndpoint); // Output: /api/users/123

Add your comment