Last active
May 24, 2018 13:30
-
-
Save crdrost/347bc0613860c0c67644ccb4bcfdb748 to your computer and use it in GitHub Desktop.
Tester for a validateRoutePath function that I released to nestjs/swagger.
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
const isUndefined = obj => typeof obj === 'undefined' | |
const validatePath = path => path.charAt(0) !== '/' ? '/' + path : path; | |
const pathToRegexp = require('path-to-regexp'); | |
function validateRoutePathNew(path) { | |
if (isUndefined(path)) { | |
return ''; | |
} | |
let pathWithParams = ''; | |
for (const item of pathToRegexp.parse(path)) { | |
if (typeof item === 'string') { | |
pathWithParams += item; | |
} else { | |
pathWithParams += `${item.prefix}{${item.name}}`; | |
} | |
} | |
return pathWithParams === '/' ? '' : validatePath(pathWithParams); | |
} | |
function validateRoutePathOld(path) { | |
if (isUndefined(path)) { | |
return ''; | |
} | |
const pathWithParams = path.replace(/([:].*?[^\/]*)/g, str => { | |
str = str.replace(/\(.*\)$/, ''); // remove any regex in the param | |
return `{${str.slice(1, str.length)}}`; | |
}); | |
return pathWithParams === '/' ? '' : validatePath(pathWithParams); | |
} | |
const tests = [ | |
"/hi/:hows/:it/:goin", | |
"sorry/you/couldnt/:get.:through", | |
"please/leave/your/name", | |
"/", | |
"and/", | |
"/your/:number(\\d+)", | |
"", | |
"/and/we'll/:get.:back/:to/:you" | |
] | |
function run(name, fn) { | |
console.log('# ' + name ); | |
const prefixWidth = tests.map(x => x.length).reduce((x, y) => Math.max(x, y), -1) + 6; | |
for (const t of tests) { | |
let line = ' ' + t; | |
while (line.length < prefixWidth) | |
line += ' '; | |
line += '=> ' | |
line += fn(t); | |
console.log(line) | |
} | |
console.log(); | |
} | |
run('Old Style', validateRoutePathOld); | |
run('New Style', validateRoutePathNew); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment