1. /**
  2. * Flattens a structure of API endpoints with manual overrides.
  3. *
  4. * @param {object} apiEndpoints - The API endpoint structure to flatten.
  5. * @param {object} overrides - An object containing manual overrides for specific endpoints.
  6. * @returns {object} - The flattened API endpoint structure.
  7. */
  8. function flattenApiEndpoints(apiEndpoints, overrides) {
  9. const flattened = {};
  10. function traverse(current, path) {
  11. for (const key in current) {
  12. if (current.hasOwnProperty(key)) {
  13. const newPath = path ? `${path}.${key}` : key;
  14. if (typeof current[key] === 'object' && current[key] !== null) {
  15. traverse(current[key], newPath);
  16. } else {
  17. // Apply override if present
  18. if (overrides && overrides[newPath]) {
  19. flattened[newPath] = overrides[newPath];
  20. } else {
  21. flattened[newPath] = current[key];
  22. }
  23. }
  24. }
  25. }
  26. }
  27. traverse(apiEndpoints, '');
  28. return flattened;
  29. }
  30. // Example Usage (can be uncommented for testing)
  31. /*
  32. const apiEndpoints = {
  33. '/users': {
  34. 'get': {
  35. 'url': '/api/users',
  36. 'method': 'GET'
  37. },
  38. '/create': {
  39. 'url': '/api/users',
  40. 'method': 'POST'
  41. }
  42. },
  43. '/products': {
  44. 'get': {
  45. 'url': '/api/products',
  46. 'method': 'GET'
  47. }
  48. }
  49. };
  50. const overrides = {
  51. '/users.get': { 'url': '/new/api/users' },
  52. '/products.get': { 'method': 'HEAD' }
  53. };
  54. const flattenedEndpoints = flattenApiEndpoints(apiEndpoints, overrides);
  55. console.log(JSON.stringify(flattenedEndpoints, null, 2));
  56. */

Add your comment