UNPKG

@axway/api-builder-uri-utils

Version:

A collection of URI utility functions for API Builder

44 lines (41 loc) 1.86 kB
/** * Express.js supports regex routing. For example, '/ab+cd' would match "abcd", * "abxcd", etc. (see http://expressjs.com/en/guide/routing.html#route-paths). * This method will escape regex characters in `path` so that they are not * accidentally interpreted as regex. In addition, this needs to avoid escaping * the `?` because it is an optional parameter in express (when the fragment * starts with `:`). * * As an example, consider "A(B)". This URI component does not require * escaping. `encodeURI` returns "A(B)". However, as an express URI, this * would be interpreted as a regular expression. To avoid that, this will * escape the path "A[(]B[)]". * * @param {string} path - The path to escape. * @return {string} The escaped path. */ function escapeExpressRegex(path) { // https://expressjs.com/en/guide/routing.html return path.replace(/([()*+])/g, '[$1]') // express regex escape // The following code is questionable. It describes a literal ? in an // express path. You can NEVER hit a path with a literal question mark // since this represents the query portion of the string which will be // stripped before the path matching takes place. You cannot provide an // encoded question mark either since this will not match a literal one. // https://tools.ietf.org/html/rfc3986#page-22 // fought with regex for a while and gave up - this took 2m to write ;) // it is going to split the path, then find any part that is not an // express parameter and then escape the ?. .split('/').map((part) => { if (!part.startsWith(':') && part.includes('?')) { return part.replace(/\?/g, '[?]'); } else if (part.startsWith(':') && part.includes('?') && !part.endsWith('?')) { return part.replace(/\?/g, '[?]'); } return part; }).join('/'); } module.exports = escapeExpressRegex;