Browse Source

feat: avoid breaking change in route handler

pull/4445/head
Arman Ozak 6 years ago
parent
commit
b4a47df4cf
  1. 30
      npm/ng-packs/packages/core/src/lib/handlers/routes.handler.ts
  2. 27
      npm/ng-packs/packages/core/src/lib/tests/routes.handler.spec.ts

30
npm/ng-packs/packages/core/src/lib/handlers/routes.handler.ts

@ -1,5 +1,6 @@
import { Injectable, Optional } from '@angular/core';
import { Router } from '@angular/router';
import { ABP } from '../models';
import { RoutesService } from '../services/routes.service';
@Injectable({
@ -11,15 +12,34 @@ export class RoutesHandler {
}
addRoutes() {
this.router?.config.forEach(({ path, data }) => {
if (!data) return;
this.router?.config.forEach(({ path = '', data }) => {
if (!data?.routes) return;
if (data.route) {
this.routes.add([{ path: '/' + path, ...data.route }]);
if (Array.isArray(data.routes)) {
this.routes.add(data.routes);
return;
}
if (data.routes) this.routes.add(data.routes);
const routes = flatRoutes([{ ...data.routes, path }], { path: '' });
this.routes.add(routes);
});
}
}
function flatRoutes(routes: RouteDef[], parent: any) {
if (!routes) return [];
return routes.reduce((acc, route) => {
const current = {
...route,
parentName: parent.name,
path: parent.path + '/' + route.path,
};
acc.push(current, ...flatRoutes(current.children, current));
return acc;
}, []);
}
type RouteDef = ABP.Route & { children: RouteDef[] };

27
npm/ng-packs/packages/core/src/lib/tests/routes.handler.spec.ts

@ -3,36 +3,13 @@ import { RoutesHandler } from '../handlers';
import { RoutesService } from '../services';
describe('Routes Handler', () => {
describe('#add', () => {
it('should add routes from router config', () => {
const config = [
{ path: 'x' },
{ path: '', data: { route: { name: 'Foo' } } },
{ path: 'bar', data: { route: { name: 'Bar' } } },
{ data: { routes: [{ path: '/baz', name: 'Baz' }] } },
];
const foo = [{ path: '/', name: 'Foo' }];
const bar = [{ path: '/bar', name: 'Bar' }];
const baz = [{ path: '/baz', name: 'Baz' }];
const routes = [];
const add = jest.fn(routes.push.bind(routes));
const mockRoutesService = ({ add } as unknown) as RoutesService;
const mockRouter = ({ config } as unknown) as Router;
const handler = new RoutesHandler(mockRoutesService, mockRouter);
expect(add).toHaveBeenCalledTimes(3);
expect(routes).toEqual([foo, bar, baz]);
});
});
describe('#add', () => {
it('should add routes from router config', () => {
const config = [
{ path: 'x' },
{ path: 'y', data: {} },
{ path: '', data: { route: { name: 'Foo' } } },
{ path: 'bar', data: { route: { name: 'Bar' } } },
{ path: '', data: { routes: { name: 'Foo' } } },
{ path: 'bar', data: { routes: { name: 'Bar' } } },
{ data: { routes: [{ path: '/baz', name: 'Baz' }] } },
];
const foo = [{ path: '/', name: 'Foo' }];

Loading…
Cancel
Save