@nestjs/core
Version:
The core of NestJS, a TypeScript framework for Node.js backends: modules, dependency injection and the request pipeline, on Express, Fastify or node:http.
72 lines (71 loc) • 3.17 kB
JavaScript
import { RouteConflictDetector, } from './route-conflict-detector.js';
/**
* Static utility class that orders resolved routes by specificity so the
* underlying HTTP adapter registers more specific patterns first.
* Stateless — every method takes everything it needs as parameters.
*/
export class RouteSpecificitySorter {
/**
* Lower rank means more specific. A literal segment beats one mixing
* text and params (`v:version`), which beats a named param, which beats
* a named wildcard. A position that is absent on one side means the
* path is shorter at that point. A shorter path with a wildcard is the
* least specific of all (`missing`), as the wildcard can absorb the
* extra segments. Without one, it ranks after a literal but before the
* other kinds (`end`): those can sit in an optional group
* (`/users{/:id}`, `/{*path}`) and then also match the shorter path.
*/
static SEGMENT_KIND_RANK = {
literal: 0,
end: 1,
mixed: 2,
param: 3,
wildcard: 4,
missing: 5,
};
/**
* Returns a new array of routes sorted from most-specific to
* least-specific. Routes that tie on specificity keep their original
* declaration order.
*/
static sort(routes) {
const decoratedRoutes = routes.map((route, declarationIndex) => ({
route,
declarationIndex,
segments: RouteConflictDetector.tokenizePath(route.path),
}));
decoratedRoutes.sort((leftEntry, rightEntry) => {
const specificityDelta = RouteSpecificitySorter.comparePathSpecificity(leftEntry.segments, rightEntry.segments);
if (specificityDelta !== 0)
return specificityDelta;
return leftEntry.declarationIndex - rightEntry.declarationIndex;
});
return decoratedRoutes.map(decoratedEntry => decoratedEntry.route);
}
static comparePathSpecificity(leftSegments, rightSegments) {
const longestPathLength = Math.max(leftSegments.length, rightSegments.length);
const leftEndKind = RouteSpecificitySorter.getEndKind(leftSegments);
const rightEndKind = RouteSpecificitySorter.getEndKind(rightSegments);
let specificityDelta = 0;
Array.from({ length: longestPathLength }).forEach((_, segmentIndex) => {
if (specificityDelta !== 0)
return;
const leftKind = leftSegments[segmentIndex]?.kind ?? leftEndKind;
const rightKind = rightSegments[segmentIndex]?.kind ?? rightEndKind;
const leftRank = RouteSpecificitySorter.rankSegmentByKind(leftKind);
const rightRank = RouteSpecificitySorter.rankSegmentByKind(rightKind);
if (leftRank !== rightRank) {
specificityDelta = leftRank - rightRank;
}
});
return specificityDelta;
}
static getEndKind(segments) {
return segments.some(segment => segment.kind === 'wildcard')
? 'missing'
: 'end';
}
static rankSegmentByKind(kind) {
return RouteSpecificitySorter.SEGMENT_KIND_RANK[kind];
}
}