Skip to content

Commit

Permalink
update(@nestjs) increase test coverage, update package dependencies
Browse files Browse the repository at this point in the history
  • Loading branch information
kamil.mysliwiec committed Jul 23, 2017
1 parent b79eda2 commit 260fd56
Show file tree
Hide file tree
Showing 56 changed files with 1,227 additions and 208 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ npm-debug.log
# example
/quick-start
/example_dist
/example

# tests
/test
Expand Down
1 change: 0 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,4 @@ before_script:
- sh -e /etc/init.d/xvfb start
script:
- npm test
- npm run build
after_success: npm run coverage
2 changes: 1 addition & 1 deletion example/modules/users/roles.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ import { Guard, CanActivate } from '@nestjs/common';
@Guard()
export class RolesGuard implements CanActivate {
public async canActivate() {
return await Promise.resolve(false);
return await Promise.resolve(true);
}
}
9 changes: 6 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "nestjs",
"version": "3.0.0",
"version": "4.0.0",
"description": "Modern, fast, powerful node.js web framework",
"main": "index.js",
"scripts": {
Expand Down Expand Up @@ -48,18 +48,20 @@
"@nestjs/testing": "*",
"@nestjs/websockets": "*",
"cli-color": "^1.1.0",
"engine.io-client": "^3.1.1",
"express": "^4.14.0",
"iterare": "0.0.8",
"json-socket": "^0.2.1",
"opencollective": "^1.0.3",
"redis": "^2.7.1",
"reflect-metadata": "^0.1.10",
"rxjs": "^5.4.2",
"socket.io": "^1.7.2",
"socket.io": "^1.7.4",
"typescript": "^2.4.1"
},
"devDependencies": {
"@types/chai": "^3.4.34",
"@types/chai": "^3.5.2",
"@types/chai-as-promised": "0.0.31",
"@types/express": "^4.0.35",
"@types/mocha": "^2.2.38",
"@types/node": "^7.0.5",
Expand All @@ -70,6 +72,7 @@
"awesome-typescript-loader": "^3.0.0-beta.18",
"body-parser": "^1.17.2",
"chai": "^3.5.0",
"chai-as-promised": "^7.1.1",
"concurrently": "^3.4.0",
"core-js": "^2.4.1",
"coveralls": "^2.11.16",
Expand Down
4 changes: 2 additions & 2 deletions src/common/interfaces/nest-application.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { INestMicroservice, ExceptionFilter, PipeTransform } from './index';
import { WebSocketAdapter } from './web-socket-adapter.interface';

export interface INestApplication {
init(): void;
listen(port: number, callback?: () => void);
init(): Promise<void>;
listen(port: number, callback?: () => void): Promise<any>;
setGlobalPrefix(prefix: string): void;
useWebSocketAdapter(adapter: WebSocketAdapter): void;
connectMicroservice(config: MicroserviceConfiguration): INestMicroservice;
Expand Down
2 changes: 1 addition & 1 deletion src/common/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@nestjs/common",
"version": "2.0.3",
"version": "4.0.0",
"description": "Nest - modern, fast, powerful node.js web framework (@common)",
"author": "Kamil Mysliwiec",
"license": "MIT",
Expand Down
26 changes: 26 additions & 0 deletions src/common/test/utils/use-guards.decorator.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import 'reflect-metadata';
import { expect } from 'chai';
import { UseGuards } from '../../utils/decorators/use-guards.decorator';
import { GUARDS_METADATA } from './../../constants';

describe('@UseGuards', () => {
const guards = [ 'guard1', 'guard2' ];

@UseGuards(...guards as any) class Test {}

class TestWithMethod {
@UseGuards(...guards as any)
public static test() {}
}

it('should enhance class with expected guards array', () => {
const metadata = Reflect.getMetadata(GUARDS_METADATA, Test);
expect(metadata).to.be.eql(guards);
});

it('should enhance method with expected guards array', () => {
const metadata = Reflect.getMetadata(GUARDS_METADATA, TestWithMethod.test);
expect(metadata).to.be.eql(guards);
});

});
9 changes: 2 additions & 7 deletions src/core/guards/guards-consumer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,12 @@ import { isUndefined, isFunction, isNil, isEmpty } from '@nestjs/common/utils/sh
import { Controller } from '@nestjs/common/interfaces';
import { CanActivate, HttpStatus } from '@nestjs/common';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';
import { HttpException } from '../index';
import { FORBIDDEN_MESSAGE } from './constants';
import 'rxjs/add/operator/toPromise';

export class GuardsConsumer {
public async tryActivate(
guards: CanActivate[],
data: any,
instance: Controller,
callback: (...args) => any): Promise<boolean> {

public async tryActivate(guards: CanActivate[], data, instance: Controller, callback: (...args) => any): Promise<boolean> {
if (!guards || isEmpty(guards)) {
return true;
}
Expand Down
16 changes: 4 additions & 12 deletions src/core/injector/injector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ export class Injector {

const instances = await Promise.all(args.map(async (param) => {
const paramWrapper = await this.resolveSingleParam<T>(wrapper, param, module, context);
if (paramWrapper.isExported && !paramWrapper.isResolved) {
if (!paramWrapper.isResolved) {
isResolved = false;
}
return paramWrapper.instance;
Expand Down Expand Up @@ -142,7 +142,7 @@ export class Injector {
const components = module.components;
const instanceWrapper = await this.scanForComponent(components, name, module, wrapper, context);

if (!instanceWrapper.isResolved && !instanceWrapper.isExported) {
if (!instanceWrapper.isResolved) {
await this.loadInstanceOfComponent(instanceWrapper, module);
}
if (instanceWrapper.async) {
Expand All @@ -162,18 +162,10 @@ export class Injector {

public async scanForComponentInExports(components: Map<string, any>, name: any, module: Module, metatype, context: Module[] = []) {
const instanceWrapper = await this.scanForComponentInRelatedModules(module, name, context);
if (!isNil(instanceWrapper)) {
return instanceWrapper;
}
const { exports } = module;
if (!exports.has(metatype.name)) {
if (isNil(instanceWrapper)) {
throw new UnknownDependenciesException(metatype.name);
}
return {
instance: null,
isResolved: false,
isExported: true,
};
return instanceWrapper;
}

public async scanForComponentInScopes(context: Module[], name: any, metatype) {
Expand Down
6 changes: 4 additions & 2 deletions src/core/injector/module-token-factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@ export class ModuleTokenFactory {
public getScopeStack(scope: NestModuleMetatype[]): string[] {
const reversedScope = scope.reverse();
const firstGlobalIndex = reversedScope.findIndex((s) => this.reflectScope(s) === 'global');
const scopeStack = scope.reverse().slice(scope.length - firstGlobalIndex - 1);
return scopeStack.map((module) => module.name);
scope.reverse();
const stack = firstGlobalIndex >= 0 ?
scope.slice(scope.length - firstGlobalIndex - 1) : scope;
return stack.map((module) => module.name);
}

private reflectScope(metatype: NestModuleMetatype) {
Expand Down
37 changes: 22 additions & 15 deletions src/core/injector/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,10 @@ export class Module {
}

public addInjectable(injectable: Metatype<Injectable>) {
if (this.isCustomProvider(injectable)) {
this.addCustomProvider(injectable, this._injectables);
return;
}
this._injectables.set(injectable.name, {
name: injectable.name,
metatype: injectable,
Expand All @@ -97,8 +101,8 @@ export class Module {
}

public addComponent(component: ComponentMetatype) {
if (this.isCustomComponent(component)) {
this.addCustomComponent(component);
if (this.isCustomProvider(component)) {
this.addCustomProvider(component, this._components);
return;
}
this._components.set((component as Metatype<Injectable>).name, {
Expand All @@ -109,21 +113,21 @@ export class Module {
});
}

public isCustomComponent(component: ComponentMetatype): component is CustomClass | CustomFactory | CustomValue {
public isCustomProvider(component: ComponentMetatype): component is CustomClass | CustomFactory | CustomValue {
return !isNil((component as CustomComponent).provide);
}

public addCustomComponent(component: CustomFactory | CustomValue | CustomClass) {
public addCustomProvider(component: CustomFactory | CustomValue | CustomClass, collection: Map<string, any>) {
const { provide } = component;
const name = isFunction(provide) ? provide.name : provide;
const comp = {
...component,
name,
};

if (this.isCustomClass(comp)) this.addCustomClass(comp);
else if (this.isCustomValue(comp)) this.addCustomValue(comp);
else if (this.isCustomFactory(comp)) this.addCustomFactory(comp);
if (this.isCustomClass(comp)) this.addCustomClass(comp, collection);
else if (this.isCustomValue(comp)) this.addCustomValue(comp, collection);
else if (this.isCustomFactory(comp)) this.addCustomFactory(comp, collection);
}

public isCustomClass(component): component is CustomClass {
Expand All @@ -138,19 +142,19 @@ export class Module {
return !isUndefined((component as CustomFactory).useFactory);
}

public addCustomClass(component: CustomClass) {
public addCustomClass(component: CustomClass, collection: Map<string, any>) {
const { provide, name, useClass } = component;
this._components.set(name, {
collection.set(name, {
name,
metatype: useClass,
instance: null,
isResolved: false,
});
}

public addCustomValue(component: CustomValue) {
public addCustomValue(component: CustomValue, collection: Map<string, any>) {
const { provide, name, useValue: value } = component;
this._components.set(name, {
collection.set(name, {
name,
metatype: null,
instance: value,
Expand All @@ -160,9 +164,9 @@ export class Module {
});
}

public addCustomFactory(component: CustomFactory) {
public addCustomFactory(component: CustomFactory, collection: Map<string, any>) {
const { provide, name, useFactory: factory, inject } = component;
this._components.set(name, {
collection.set(name, {
name,
metatype: factory as any,
instance: null,
Expand All @@ -173,7 +177,7 @@ export class Module {
}

public addExportedComponent(exportedComponent: ComponentMetatype) {
if (this.isCustomComponent(exportedComponent)) {
if (this.isCustomProvider(exportedComponent)) {
this.addCustomExportedComponent(exportedComponent);
return;
}
Expand Down Expand Up @@ -201,7 +205,10 @@ export class Module {
}

public replace(toReplace, options) {
this.addComponent({
if (options.isComponent) {
return this.addComponent({ provide: toReplace, ...options });
}
this.addInjectable({
provide: toReplace,
...options,
});
Expand Down
30 changes: 4 additions & 26 deletions src/core/middlewares/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { Metatype, MiddlewaresConsumer } from '@nestjs/common/interfaces';
import { MiddlewareConfigProxy } from '@nestjs/common/interfaces/middlewares';
import { RoutesMapper } from './routes-mapper';
import { NestMiddleware } from '@nestjs/common';
import { filterMiddlewares } from './utils';

export class MiddlewareBuilder implements MiddlewaresConsumer {
private readonly middlewaresCollection = new Set<MiddlewareConfiguration>();
Expand Down Expand Up @@ -54,10 +55,10 @@ export class MiddlewareBuilder implements MiddlewaresConsumer {
private readonly builder: MiddlewareBuilder,
middlewares,
) {
this.includedRoutes = this.filterMiddlewares(middlewares);
this.includedRoutes = filterMiddlewares(middlewares);
}

public with(...args): this {
public with(...args): MiddlewareConfigProxy {
this.contextArgs = args;
return this;
}
Expand All @@ -81,28 +82,5 @@ export class MiddlewareBuilder implements MiddlewaresConsumer {
private mapRoutesToFlatList(forRoutes) {
return forRoutes.reduce((a, b) => a.concat(b));
}

private filterMiddlewares(middlewares) {
return [].concat(middlewares)
.filter(isFunction)
.map((middleware) => {
if (this.isClass(middleware)) {
return middleware;
}
return AssignToken(class {
public resolve = (...args) => (req, res, next) => middleware(req, res, next);
});
});
}

private isClass(middleware) {
return middleware.toString().substring(0, 5) === 'class';
}
};
}

const AssignToken = (metatype): Metatype<any> => {
this.id = this.id || 1;
Object.defineProperty(metatype, 'name', { value: ++this.id });
return metatype;
};
}
27 changes: 27 additions & 0 deletions src/core/middlewares/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { isFunction } from '@nestjs/common/utils/shared.utils';
import { Metatype } from '@nestjs/common/interfaces';

export const filterMiddlewares = (middlewares) => {
return [].concat(middlewares)
.filter(isFunction)
.map((middleware) => mapToClass(middleware));
};

export const mapToClass = (middleware) => {
if (this.isClass(middleware)) {
return middleware;
}
return assignToken(class {
public resolve = (...args) => (req, res, next) => middleware(req, res, next);
});
};

export const isClass = (middleware) => {
return middleware.toString().substring(0, 5) === 'class';
};

export const assignToken = (metatype): Metatype<any> => {
this.id = this.id || 1;
Object.defineProperty(metatype, 'name', { value: ++this.id });
return metatype;
};
15 changes: 10 additions & 5 deletions src/core/nest-factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,16 @@ export class NestFactory {
}

private static async initialize(module) {
this.logger.log(messages.APPLICATION_START);
await ExceptionsZone.asyncRun(async () => {
this.dependenciesScanner.scan(module);
await this.instanceLoader.createInstancesOfDependencies();
});
try {
this.logger.log(messages.APPLICATION_START);
await ExceptionsZone.asyncRun(async () => {
this.dependenciesScanner.scan(module);
await this.instanceLoader.createInstancesOfDependencies();
});
}
catch (e) {
process.abort();
}
}

private static createProxy(target) {
Expand Down
Loading

0 comments on commit 260fd56

Please sign in to comment.