1. function matchHttpPattern(request, patterns) {
  2. for (const pattern of patterns) {
  3. if (matches(request, pattern)) {
  4. return pattern.dryRun; // Return the dryRun flag if the pattern matches
  5. }
  6. }
  7. return null; // No match found
  8. }
  9. function matches(request, pattern) {
  10. // Simple pattern matching logic (can be extended)
  11. if (pattern.method && request.method !== pattern.method) return false;
  12. if (pattern.url && request.url !== pattern.url) return false;
  13. if (pattern.headers) {
  14. for (const header in pattern.headers) {
  15. if (request.headers && request.headers[header] !== pattern.headers[header]) return false;
  16. }
  17. }
  18. return true;
  19. }
  20. //Example Usage
  21. const patterns = [
  22. {
  23. method: 'GET',
  24. url: '/api/users',
  25. dryRun: true,
  26. headers: {
  27. 'Authorization': 'Bearer token'
  28. }
  29. },
  30. {
  31. method: 'POST',
  32. url: '/api/products',
  33. dryRun: false,
  34. headers: {
  35. 'Content-Type': 'application/json'
  36. }
  37. },
  38. {
  39. method: 'GET',
  40. url: '/health',
  41. dryRun: true
  42. }
  43. ];
  44. // Simulate an HTTP request
  45. const request1 = { method: 'GET', url: '/api/users', headers: { 'Authorization': 'Bearer token' } };
  46. const request2 = { method: 'POST', url: '/api/products', headers: { 'Content-Type': 'application/json' } };
  47. const request3 = { method: 'GET', url: '/health' };
  48. const request4 = { method: 'GET', url: '/api/users', headers: { 'Authorization': 'Bearer another_token' } };
  49. console.log("Request 1 matches:", matchHttpPattern(request1, patterns)); // Output: true
  50. console.log("Request 2 matches:", matchHttpPattern(request2, patterns)); // Output: false
  51. console.log("Request 3 matches:", matchHttpPattern(request3, patterns)); // Output: true
  52. console.log("Request 4 matches:", matchHttpPattern(request4, patterns)); // Output: false

Add your comment