Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(@nestjs/core): Add RouterModule to the core #3489

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions packages/common/test/utils/shared.utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,10 +88,20 @@ describe('Shared utils', () => {
it('should returns same path', () => {
expect(validatePath('/nope')).to.be.eql('/nope');
});
it('should returns empty path', () => {
expect(validatePath('')).to.be.eql('');
expect(validatePath(null)).to.be.eql('');
expect(validatePath(undefined)).to.be.eql('');
it('should remove all trailing slashes at the end of the path', () => {
expect(validatePath('path/')).to.be.eql('/path');
expect(validatePath('path///')).to.be.eql('/path');
expect(validatePath('/path/path///')).to.be.eql('/path/path');
});
it('should replace all slashes with only one slash', () => {
expect(validatePath('////path/')).to.be.eql('/path');
expect(validatePath('///')).to.be.eql('/');
expect(validatePath('/path////path///')).to.be.eql('/path/path');
});
it('should returns / for empty path', () => {
expect(validatePath('')).to.be.eql('/');
expect(validatePath(null)).to.be.eql('/');
expect(validatePath(undefined)).to.be.eql('/');
});
});
describe('isNil', () => {
Expand Down
6 changes: 5 additions & 1 deletion packages/common/utils/shared.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,11 @@ export const isPlainObject = (fn: any): fn is object => {
);
};
export const validatePath = (path?: string): string =>
path ? (path.charAt(0) !== '/' ? '/' + path : path) : '';
path
? path.startsWith('/')
? ('/' + path.replace(/\/+$/, '')).replace(/\/+/g, '/')
: '/' + path.replace(/\/+$/, '')
: '/';
export const isFunction = (fn: any): boolean => typeof fn === 'function';
export const isString = (fn: any): fn is string => typeof fn === 'string';
export const isConstructor = (fn: any): boolean => fn === 'constructor';
Expand Down
25 changes: 25 additions & 0 deletions packages/core/router/interfaces/routes.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Type } from '@nestjs/common';

/**
* Defines the Routes Tree
* - `path` - a string describe the Module path which will be applied
* to all it's controllers and childs
* - `module` - the parent Module.
* - `children` - an array of child Modules.
*/
export interface Route {
path: string;
module?: Type<any>;
children?: Routes | Type<any>[];
}

/**
* Defines the Routes Tree
* - `path` - a string describe the Module path which will be applied
* to all it's controllers and childs
* - `module` - the parent Module.
* - `children` - an array of child Modules.
*
* @publicapi
*/
export type Routes = Route[];
6 changes: 5 additions & 1 deletion packages/core/router/router-explorer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,11 @@ export class RouterExplorer {
prefix?: string,
): string {
let path = Reflect.getMetadata(PATH_METADATA, metatype);
if (prefix) path = prefix + this.validateRoutePath(path);
if (prefix) {
path = prefix + this.validateRoutePath(path);
// Override the metadata with the new path
Reflect.defineMetadata(PATH_METADATA, path, metatype);
}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think doing this would solve all integration issues with any other packages that depend on routes

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for example the swagger integration issues and also this issue nestjsx/nest-router#5

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very uncommon but still: what if I have the same controller used in 2 modules? In this case, I'd override the metadata twice.

return this.validateRoutePath(path);
}

Expand Down
36 changes: 36 additions & 0 deletions packages/core/router/router.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { Module, DynamicModule } from '@nestjs/common';
import { validatePath } from '@nestjs/common/utils/shared.utils';
import { MODULE_PATH } from '@nestjs/common/constants';
import { Routes } from './interfaces/routes.interface';
import { flatRoutes } from './utils/flat-routes.util';

/**
* A Utility Module to Organize your Routes,
*
* @publicApi
*/
@Module({})
export class RouterModule {
/**
* takes an array of modules and organize them in hierarchy way
* @param {Routes} routes Array of Routes
* @publicapi
*/
static register(routes: Routes): DynamicModule {
RouterModule.buildPathMap(routes);
return {
module: RouterModule,
};
}

private static buildPathMap(routes: Routes) {
const flattenRoutes = flatRoutes(routes);
flattenRoutes.forEach(route => {
Reflect.defineMetadata(
MODULE_PATH,
validatePath(route.path),
route.module,
);
});
}
}
28 changes: 28 additions & 0 deletions packages/core/router/utils/flat-routes.util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Routes } from '../interfaces/routes.interface';
import { validatePath } from '@nestjs/common/utils/shared.utils';

export function flatRoutes(routes: Routes, result = []) {
routes.forEach(element => {
if (element.module && element.path) {
result.push(element);
}
if (element.children) {
const childrenRef = element.children as Routes;
childrenRef.forEach(child => {
if (!(typeof child === 'string') && child.path) {
child.path = validatePath(
validatePath(element.path) + validatePath(child.path),
);
} else {
result.push({ path: element.path, module: child });
}
});
return flatRoutes(childrenRef, result);
}
});
result.forEach(route => {
// clean up
delete route.children;
});
return result;
}
74 changes: 74 additions & 0 deletions packages/core/test/router/router.module.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { RouterModule } from '../../router/router.module';
import { Module, Controller } from '@nestjs/common';
import { MODULE_PATH } from '@nestjs/common/constants';
import { Test } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import { Routes } from '../../router/interfaces/routes.interface';
import { expect } from 'chai';

describe('RouterModule', () => {
let app: INestApplication;

@Controller('/parent-controller')
class ParentController {}
@Controller('/child-controller')
class ChildController {}
@Controller('no-slash-controller')
class NoSlashController {}

class UnknownController {}
@Module({ controllers: [ParentController] })
class ParentModule {}

@Module({ controllers: [ChildController] })
class ChildModule {}

@Module({})
class AuthModule {}
@Module({})
class PaymentsModule {}

@Module({ controllers: [NoSlashController] })
class NoSlashModule {}

const routes1: Routes = [
{
path: 'parent',
module: ParentModule,
children: [
{
path: 'child',
module: ChildModule,
},
],
},
];

const routes2: Routes = [
{ path: 'v1', children: [AuthModule, PaymentsModule] },
];

@Module({
imports: [ParentModule, ChildModule, RouterModule.register(routes1)],
})
class MainModule {}

@Module({
imports: [AuthModule, PaymentsModule, RouterModule.register(routes2)],
})
class AppModule {}

it('should add Path Metadata to all Routes', () => {
const parentPath = Reflect.getMetadata(MODULE_PATH, ParentModule);
const childPath = Reflect.getMetadata(MODULE_PATH, ChildModule);
expect(parentPath).to.be.equal('/parent');
expect(childPath).to.be.equal('/parent/child');
});

it('should add paths even we omitted the module key', () => {
const authPath = Reflect.getMetadata(MODULE_PATH, AuthModule);
const paymentPath = Reflect.getMetadata(MODULE_PATH, PaymentsModule);
expect(authPath).to.be.equal('/v1');
expect(paymentPath).to.be.equal('/v1');
});
});
87 changes: 87 additions & 0 deletions packages/core/test/router/utils/flat-routes.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { expect } from 'chai';
import { flatRoutes } from '../../../router/utils/flat-routes.util';
import { Module } from '@nestjs/common';
describe('FlatRoutes', () => {
it('should flat all Routes, and we could also ommit the path', () => {
@Module({})
class ParentModule {}
@Module({})
class ChildModule {}
@Module({})
class ChildChildModule {}
@Module({})
class ChildModule2 {}
@Module({})
class ParentChildModule {}
@Module({})
class ChildChildModule2 {}
@Module({})
class AuthModule {}
@Module({})
class CatsModule {}
@Module({})
class DogsModule {}

@Module({})
class AuthModule2 {}
@Module({})
class CatsModule2 {}
@Module({})
class CatsModule3 {}
@Module({})
class AuthModule3 {}
const routes = [
{
path: '/parent',
module: ParentModule,
children: [
{
path: '/child',
module: ChildModule,
children: [
{ path: '/child2', module: ChildModule2 },
{
path: '/parentchild',
module: ParentChildModule,
children: [
{
path: '/childchild',
module: ChildChildModule,
children: [
{ path: '/child2child', module: ChildChildModule2 },
],
},
],
},
],
},
],
},
{ path: '/v1', children: [AuthModule, CatsModule, DogsModule] },
{ path: '/v2', children: [AuthModule2, CatsModule2] },
{ path: '/v3', children: [AuthModule3, CatsModule3] },
];
const expectedRoutes = [
{ path: '/parent', module: ParentModule },
{ path: '/parent/child', module: ChildModule },
{ path: '/parent/child/child2', module: ChildModule2 },
{ path: '/parent/child/parentchild', module: ParentChildModule },
{
path: '/parent/child/parentchild/childchild',
module: ChildChildModule,
},
{
path: '/parent/child/parentchild/childchild/child2child',
module: ChildChildModule2,
},
{ path: '/v1', module: AuthModule },
{ path: '/v1', module: CatsModule },
{ path: '/v1', module: DogsModule },
{ path: '/v2', module: AuthModule2 },
{ path: '/v2', module: CatsModule2 },
{ path: '/v3', module: AuthModule3 },
{ path: '/v3', module: CatsModule3 },
];
expect(flatRoutes(routes)).to.be.eql(expectedRoutes);
});
});