error if routes clash - fixes #33

This commit is contained in:
Rich Harris
2017-12-20 20:46:28 -05:00
parent 8925e541d5
commit f50d3c4262
2 changed files with 54 additions and 9 deletions

View File

@@ -1,7 +1,7 @@
const path = require('path');
module.exports = function create_matchers(files) {
return files
const routes = files
.map(file => {
if (/(^|\/|\\)_/.test(file)) return;
@@ -47,9 +47,31 @@ module.exports = function create_matchers(files) {
})
.filter(Boolean)
.sort((a, b) => {
return (
(a.dynamic.length - b.dynamic.length) || // match static paths first
(b.parts.length - a.parts.length) // match longer paths first
);
let same = true;
for (let i = 0; true; i += 1) {
const a_part = a.parts[i];
const b_part = b.parts[i];
if (!a_part && !b_part) {
if (same) throw new Error(`The ${a.file} and ${b.file} routes clash`);
return 0;
}
if (!a_part) return 1;
if (!b_part) return -1;
const a_is_dynamic = a_part[0] === '[';
const b_is_dynamic = b_part[0] === '[';
if (a_is_dynamic === b_is_dynamic) {
if (!a_is_dynamic) same = false;
continue;
}
return a_is_dynamic ? 1 : -1;
}
});
return routes;
}