Skip to content

Instantly share code, notes, and snippets.

@totherik
Created March 11, 2014 16:15
Show Gist options
  • Save totherik/9489139 to your computer and use it in GitHub Desktop.
Save totherik/9489139 to your computer and use it in GitHub Desktop.
Reverse Express routes.
'use strict';
var assert = require('assert');
var path2regex = require('path-to-regexp');
function reverse(route, obj) {
var keys;
keys = [];
path2regex(route, keys);
keys.forEach(function (key) {
var value, regex;
value = obj[key.name];
regex = '\\:' + key.name;
if (key.optional) {
// Include the trailing '?' in the replacement.
regex += '\\?';
if (value === undefined) {
// No value so remove potential trailing '/'
// since the path segment is optional.
value = '';
regex += '\\/?';
}
} else if (value === undefined) {
value = '';
}
route = route.replace(new RegExp(regex, 'g'), value);
});
return route;
}
var path, actual;
path = '/foo/bar/:baz';
actual = reverse(path, { baz: 10 });
assert.equal(actual, '/foo/bar/10');
path = '/foo/bar/:baz?';
actual = reverse(path, { baz: 10 });
assert.equal(actual, '/foo/bar/10');
actual = reverse(path, { baz: undefined });
assert.equal(actual, '/foo/bar/');
path = '/foo/:bar/:baz?/';
actual = reverse(path, { bar: 10, baz: 'abc' });
assert.equal(actual, '/foo/10/abc/');
path = '/foo/:bar/:baz?';
actual = reverse(path, { bar: 10, baz: undefined });
assert.equal(actual, '/foo/10/');
path = '/foo/:bar?/:baz';
actual = reverse(path, { bar: undefined, baz: 'abc' });
assert.equal(actual, '/foo/abc');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment