Last active
August 29, 2015 14:15
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Probably handy to escape ?
too since it will be used for matchers containing query strings. Basically whatever you can do to make your paths more human readable then you should do it. Try to encapsulate escaping cuz it's just plain ugly and sucks. Ya digg??
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
I would use this in conjunction with
kbaltrinic/http-backend-proxy
. In fact, that's exactly why I built it. I will probably look to integrate this intoarmw4/protractor-trials
at some point just for display purposes. Holla...