Skip to content

Instantly share code, notes, and snippets.

@armw4
Last active August 29, 2015 14:15
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 armw4/2ecec67720f938ae1a11 to your computer and use it in GitHub Desktop.
Save armw4/2ecec67720f938ae1a11 to your computer and use it in GitHub Desktop.
Naive regex builder that helps henerate url matchers for $httpBackend based on routing syntax.
# https://docs.angularjs.org/api/ngMockE2E/service/$httpBackend
### @usage
path = require './path'
urlMatcher = path '/users/:guid/helloworld/:guid'
phones = [{name: 'phone1'}, {name: 'phone2'}]
$httpBackend.whenGET(urlMatcher).respond(phones)
Most of the time you just want to match on the end of the url as opposed to the full url (host header + request path)
as base addresses typically change per environment. For example, instead of matching on https://github.com/armw4,
I'd write a matcher less brittle like /armw4$/ (only testing the end of the url, excluding the scheme,
host, port, etc.). So this will suffice.
###
placeHolders =
guid: -> "[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"
invokePlaceholderPipeline = (pattern) ->
accumalatorValue = pattern
for key, valueFactory of placeHolders
keyReplacementRegex = new RegExp ":#{key}", 'g'
accumalatorValue = accumalatorValue.replace keyReplacementRegex, valueFactory()
accumalatorValue
path = (requestPath) ->
forwardSlashesEscaped = requestPath.replace(/\//g, '\\/')
urlSelectorPattern = invokePlaceholderPipeline forwardSlashesEscaped
urlSelectorRegex = new RegExp urlSelectorPattern
module.exports = path
# sample code
actual = 'https://github.nreca.org/users/e887e740-31f2-4530-911e-4fec9be2cc45/helloworld/e887e740-31f2-4530-911e-4fec9be2cc45'
x = path '/users/:guid/helloworld/:guid'
console.log 'it"s a match mang' if x.test actual # it"s a match mang
@armw4
Copy link
Author

armw4 commented Feb 10, 2015

Snippet to escape ?:

forwardSlashesEscaped = requestPath.replace(/\//g, '\\/').replace('?', '\\?')

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