Skip to content

Commit

Permalink
fix(routes): register routes without parameters first
Browse files Browse the repository at this point in the history
  • Loading branch information
nolleto committed May 15, 2020
1 parent 554a7f4 commit 98cf921
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
27 changes: 27 additions & 0 deletions source/routes.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,5 +207,32 @@ describe('source/routes.ts', () => {
});
});
});

describe('when the same route accepts a parameter or a fixed value', () => {
const routes: RouteProperties[] = [
{ path: '/user/:id', methods: [] },
{ path: '/user/admin', methods: [] },
{ path: '/post', methods: [] },
{ path: '/post/:id/comments/:commentId', methods: [] },
{ path: '/post/:id/comments', methods: [] },
{ path: '/post/:id', methods: [] },
];

beforeEach(() => {
routeManager = new RouteManager();
routeManager.setAll(routes);
});

it('returns routes without parameter first', () => {
expect(routeManager.getAll()).toEqual([
{ path: '/user/admin', methods: [] },
{ path: '/post', methods: [] },
{ path: '/user/:id', methods: [] },
{ path: '/post/:id/comments', methods: [] },
{ path: '/post/:id', methods: [] },
{ path: '/post/:id/comments/:commentId', methods: [] },
]);
});
});
});
});
17 changes: 15 additions & 2 deletions source/routes.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Route, Method, MethodOverride } from './interfaces';
import { Route, Method, MethodOverride, RouteProperties } from './interfaces';

export function getRoutesPaths(routes: Route[]) {
return routes.map(({ path }) => path);
Expand Down Expand Up @@ -67,6 +67,18 @@ function mergeRoutesWithGlobalOverrides(
return routes;
}

function getNumberOfParameter(path: string) {
return (path.match(/:/g) ?? []).length;
}

function sortRoutesByNumberOfParameters(routes: RouteProperties[]) {
return routes.sort((routeA, routeB) => {
return (
getNumberOfParameter(routeA.path) - getNumberOfParameter(routeB.path)
);
});
}

export class RouteManager {
private routes: Route[];
private globalOverrides?: MethodOverride[];
Expand Down Expand Up @@ -98,12 +110,13 @@ export class RouteManager {
routes,
this.globalOverrides
);
const routesSorted = sortRoutesByNumberOfParameters(routesWithOverrides);

while (this.routes.length > 0) {
this.routes.pop();
}

routesWithOverrides.forEach((route) => {
routesSorted.forEach((route) => {
this.routes.push(route);
});
}
Expand Down

0 comments on commit 98cf921

Please sign in to comment.