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 all 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
2 changes: 1 addition & 1 deletion packages/core/middleware/routes-mapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export class RoutesMapper {

private validateGlobalPath(path: string): string {
const prefix = validatePath(path);
return prefix === '/' ? '' : prefix;
return prefix;
}

private validateRoutePath(path: string): string {
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[];
4 changes: 3 additions & 1 deletion packages/core/router/router-explorer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,9 @@ 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);
}
return this.validateRoutePath(path);
}

Expand Down
72 changes: 72 additions & 0 deletions packages/core/router/router.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { Module, DynamicModule } from '@nestjs/common';
import { validatePath } from '@nestjs/common/utils/shared.utils';
import { MODULE_PATH, PATH_METADATA } from '@nestjs/common/constants';
import { Controller, Type } from '@nestjs/common/interfaces';
import { Routes } from './interfaces/routes.interface';
import { flatRoutes } from './utils/flat-routes.util';
import { ModulesContainer } from '../injector';
import { UnknownElementException } from '../errors/exceptions/unknown-element.exception';

/**
* A Utility Module to Organize your Routes,
*
* @publicApi
*/
@Module({})
export class RouterModule {
// A HashMap between the route path and it's module path.
private static readonly routesContainer: Map<string, string> = new Map();
constructor(readonly modulesContainer: ModulesContainer) {
const modules = [...modulesContainer.values()];
for (const nestModule of modules) {
const modulePath: string = Reflect.getMetadata(
MODULE_PATH,
nestModule.metatype,
);
for (const route of nestModule.routes.values()) {
RouterModule.routesContainer.set(route.name, validatePath(modulePath));
}
}
}

/**
* 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,
};
}

/**
* Get the controller full route path eg: (controller's module prefix + controller's path).
*
* @param {Type<Controller>} controller the controller you need to get it's full path
*/
public static resolvePath(controller: Type<Controller>): string {
const controllerPath: string = Reflect.getMetadata(
PATH_METADATA,
controller,
);
const modulePath = RouterModule.routesContainer.get(controller.name);
if (modulePath && controllerPath) {
return validatePath(modulePath + validatePath(controllerPath));
} else {
throw new UnknownElementException(controller.name);
}
}

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;
}
111 changes: 111 additions & 0 deletions packages/core/test/router/router.module.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
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, NoSlashModule] },
];

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

@Module({
imports: [
AuthModule,
PaymentsModule,
NoSlashModule,
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');
});

describe('Full Running App', async () => {
before(async () => {
const module = await Test.createTestingModule({
imports: [MainModule, AppModule],
}).compile();
app = module.createNestApplication();
});

it('should Resolve Controllers path with its Module Path if any', async () => {
expect(RouterModule.resolvePath(ParentController)).to.be.equal(
'/parent/parent-controller',
);
expect(RouterModule.resolvePath(ChildController)).to.be.equal(
'/parent/child/child-controller',
);
});

it('should throw error when we cannot find the controller', async () => {
expect(() => RouterModule.resolvePath(UnknownController)).throw(
'Nest could not find UnknownController element (this provider does not exist in the current context)',
);
});

it('should resolve controllers path concatinated with its module path correctly', async () => {
expect(RouterModule.resolvePath(NoSlashController)).to.be.equal(
'/v1/no-slash-controller',
);
});

afterEach(async () => {
await app.close();
});
});
});
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);
});
});