sort-route-paths v1.0.0
sort-route-paths.js
Sort route paths
Current status
Usage
Sort route paths so that static routes precede dynamic routes. i.e. /foo/:id
ranked after /foo/new
.
This is the order you'd want to add the routes to express so that static routes match first i.e. request for /foo/new
is matched by /foo/new
route, not /foo/:id
.
Ranking algorithm stolen from sort-route-addresses but this implementation also puts paths in alphabetical order.
Returns a new array of the paths sorted. Does not alter original array.
const sort = require('sort-route-paths');
const paths = [
'/*',
'/:id',
'/foo',
'/foo/:id',
'/foo/bar',
'/'
];
console.log( sort(paths) );
Outputs:
[
'/',
'/foo',
'/foo/bar',
'/foo/:id',
'/:id',
'/*'
]
Sorting objects
Optional 2nd argument can be used to sort objects by a property containing the path.
With function
const routes = [
{id: 1, path: '/foo/:id'},
{id: 2, path: '/foo/new'}
];
const sortedRoutes = sort( routes, route => route.path );
Results in:
[
{id: 2, path: '/foo/new'},
{id: 1, path: '/foo/:id'}
];
With string
Or just provide property name as a string. These two are equivalent:
sort( routes, route => route.path );
sort( routes, 'path' );
Tests
Use npm test
to run the tests. Use npm run cover
to check coverage.
Changelog
See changelog.md
Issues
If you discover a bug, please raise an issue on Github. https://github.com/overlookmotel/sort-route-paths/issues
Contribution
Pull requests are very welcome. Please:
- ensure all tests pass before submitting PR
- add an entry to changelog
- add tests for new features
- document new functionality/API additions in README
6 years ago