Skip to content

Commit

Permalink
Merge c38c912 into afae462
Browse files Browse the repository at this point in the history
  • Loading branch information
kamilmysliwiec committed Aug 16, 2018
2 parents afae462 + c38c912 commit f351f98
Show file tree
Hide file tree
Showing 60 changed files with 3,892 additions and 1,154 deletions.
4 changes: 4 additions & 0 deletions .travis.yml
Expand Up @@ -2,6 +2,10 @@ language: node_js
node_js:
- "8"
- "9"
- "10"
cache:
directories:
- "node_modules"
git:
depth: 5
addons:
Expand Down
@@ -1,4 +1,5 @@
import { RuntimeException } from './runtime.exception';
import { InjectorDependencyContext } from '../../injector/injector';
export declare class UndefinedDependencyException extends RuntimeException {
constructor(type: string, index: number, length: number);
constructor(type: string, undefinedDependencyContext: InjectorDependencyContext);
}
Expand Up @@ -3,8 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
const runtime_exception_1 = require("./runtime.exception");
const messages_1 = require("../messages");
class UndefinedDependencyException extends runtime_exception_1.RuntimeException {
constructor(type, index, length) {
super(messages_1.UnknownDependenciesMessage(type, index, length));
constructor(type, undefinedDependencyContext) {
super(messages_1.UnknownDependenciesMessage(type, undefinedDependencyContext));
}
}
exports.UndefinedDependencyException = UndefinedDependencyException;
@@ -1,4 +1,5 @@
import { RuntimeException } from './runtime.exception';
import { InjectorDependencyContext } from '../../injector/injector';
export declare class UnknownDependenciesException extends RuntimeException {
constructor(type: string, index: number, length: number);
constructor(type: string, unknownDependencyContext: InjectorDependencyContext);
}
Expand Up @@ -3,8 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
const runtime_exception_1 = require("./runtime.exception");
const messages_1 = require("../messages");
class UnknownDependenciesException extends runtime_exception_1.RuntimeException {
constructor(type, index, length) {
super(messages_1.UnknownDependenciesMessage(type, index, length));
constructor(type, unknownDependencyContext) {
super(messages_1.UnknownDependenciesMessage(type, unknownDependencyContext));
}
}
exports.UnknownDependenciesException = UnknownDependenciesException;
3 changes: 2 additions & 1 deletion bundle/core/errors/messages.d.ts
@@ -1,4 +1,5 @@
export declare const UnknownDependenciesMessage: (type: string, index: number, length: number) => string;
import { InjectorDependencyContext } from '../injector/injector';
export declare const UnknownDependenciesMessage: (type: string, unknownDependencyContext: InjectorDependencyContext) => string;
export declare const InvalidMiddlewareMessage: (name: string) => string;
export declare const InvalidModuleMessage: (scope: string) => string;
export declare const UnknownExportMessage: (module: string) => string;
Expand Down
16 changes: 12 additions & 4 deletions bundle/core/errors/messages.js
@@ -1,11 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.UnknownDependenciesMessage = (type, index, length) => {
/**
* Returns the name of the dependency
* Tries to get the class name, otherwise the string value
* (= injection token). As fallback it returns '+'
* @param dependency The dependency whichs name shoul get displayed
*/
const getDependencyName = (dependency) => (dependency && dependency.name) || dependency || '+';
exports.UnknownDependenciesMessage = (type, unknownDependencyContext) => {
const { index, dependencies } = unknownDependencyContext;
let message = `Nest can't resolve dependencies of the ${type}`;
message += ` (`;
const args = new Array(length).fill('+');
args[index] = '?';
message += args.join(', ');
const dependenciesName = dependencies.map(getDependencyName);
dependenciesName[index] = '?';
message += dependenciesName.join(', ');
message += `). Please make sure that the argument at index [${index}] is available in the current context.`;
return message;
};
Expand Down
47 changes: 28 additions & 19 deletions bundle/core/injector/injector.d.ts
Expand Up @@ -13,29 +13,38 @@ export declare class Injector {
loadInstanceOfComponent(wrapper: InstanceWrapper<Injectable>, module: Module): Promise<void>;
applyDoneSubject<T>(wrapper: InstanceWrapper<T>): () => void;
loadInstance<T>(wrapper: InstanceWrapper<T>, collection: any, module: Module): Promise<void>;
resolveConstructorParams<T>(wrapper: InstanceWrapper<T>, module: Module, inject: any[], callback: (args) => void): Promise<void>;
resolveConstructorParams<T>(wrapper: InstanceWrapper<T>, module: Module, inject: InjectorDependency[], callback: (args) => void): Promise<void>;
reflectConstructorParams<T>(type: Type<T>): any[];
reflectSelfParams<T>(type: Type<T>): any[];
resolveSingleParam<T>(wrapper: InstanceWrapper<T>, param: Type<any> | string | symbol | any, {index, length}: {
index: number;
length: number;
}, module: Module): Promise<any>;
resolveSingleParam<T>(wrapper: InstanceWrapper<T>, param: Type<any> | string | symbol | any, dependencyContext: InjectorDependencyContext, module: Module): Promise<any>;
resolveParamToken<T>(wrapper: InstanceWrapper<T>, param: Type<any> | string | symbol | any): any;
resolveComponentInstance<T>(module: Module, name: any, {index, length}: {
index: number;
length: number;
}, wrapper: InstanceWrapper<T>): Promise<any>;
lookupComponent<T = any>(components: Map<string, any>, module: Module, {name, index, length}: {
name: any;
index: number;
length: number;
}, wrapper: InstanceWrapper<T>): Promise<any>;
lookupComponentInExports<T = any>(components: Map<string, any>, {name, index, length}: {
name: any;
index: number;
length: number;
}, module: Module, wrapper: InstanceWrapper<T>): Promise<any>;
resolveComponentInstance<T>(module: Module, name: any, dependencyContext: InjectorDependencyContext, wrapper: InstanceWrapper<T>): Promise<any>;
lookupComponent<T = any>(components: Map<string, any>, module: Module, dependencyContext: InjectorDependencyContext, wrapper: InstanceWrapper<T>): Promise<any>;
lookupComponentInExports<T = any>(components: Map<string, any>, dependencyContext: InjectorDependencyContext, module: Module, wrapper: InstanceWrapper<T>): Promise<any>;
lookupComponentInRelatedModules(module: Module, name: any): Promise<any>;
resolveFactoryInstance(factoryResult: any): Promise<any>;
flatMap(modules: Module[]): Module[];
}
/**
* The type of an injectable dependency
*/
export declare type InjectorDependency = Type<any> | Function | string;
/**
* Context of a dependency which gets injected by
* the injector
*/
export interface InjectorDependencyContext {
/**
* The name of the function or injection token
*/
name?: string;
/**
* The index of the dependency which gets injected
* from the dependencies array
*/
index: number;
/**
* The dependency array which gets injected
*/
dependencies: InjectorDependency[];
}
27 changes: 14 additions & 13 deletions bundle/core/injector/injector.js
Expand Up @@ -73,11 +73,11 @@ class Injector {
}
async resolveConstructorParams(wrapper, module, inject, callback) {
let isResolved = true;
const args = shared_utils_1.isNil(inject)
const dependencies = shared_utils_1.isNil(inject)
? this.reflectConstructorParams(wrapper.metatype)
: inject;
const instances = await Promise.all(args.map(async (param, index) => {
const paramWrapper = await this.resolveSingleParam(wrapper, param, { index, length: args.length }, module);
const instances = await Promise.all(dependencies.map(async (param, index) => {
const paramWrapper = await this.resolveSingleParam(wrapper, param, { index, dependencies }, module);
if (!paramWrapper.isResolved && !paramWrapper.forwardRef) {
isResolved = false;
}
Expand All @@ -94,12 +94,12 @@ class Injector {
reflectSelfParams(type) {
return Reflect.getMetadata(constants_1.SELF_DECLARED_DEPS_METADATA, type) || [];
}
async resolveSingleParam(wrapper, param, { index, length }, module) {
async resolveSingleParam(wrapper, param, dependencyContext, module) {
if (shared_utils_1.isUndefined(param)) {
throw new undefined_dependency_exception_1.UndefinedDependencyException(wrapper.name, index, length);
throw new undefined_dependency_exception_1.UndefinedDependencyException(wrapper.name, dependencyContext);
}
const token = this.resolveParamToken(wrapper, param);
return await this.resolveComponentInstance(module, shared_utils_1.isFunction(token) ? token.name : token, { index, length }, wrapper);
return await this.resolveComponentInstance(module, shared_utils_1.isFunction(token) ? token.name : token, dependencyContext, wrapper);
}
resolveParamToken(wrapper, param) {
if (!param.forwardRef) {
Expand All @@ -108,9 +108,9 @@ class Injector {
wrapper.forwardRef = true;
return param.forwardRef();
}
async resolveComponentInstance(module, name, { index, length }, wrapper) {
async resolveComponentInstance(module, name, dependencyContext, wrapper) {
const components = module.components;
const instanceWrapper = await this.lookupComponent(components, module, { name, index, length }, wrapper);
const instanceWrapper = await this.lookupComponent(components, module, Object.assign({ name }, dependencyContext), wrapper);
if (!instanceWrapper.isResolved && !instanceWrapper.forwardRef) {
await this.loadInstanceOfComponent(instanceWrapper, module);
}
Expand All @@ -119,14 +119,15 @@ class Injector {
}
return instanceWrapper;
}
async lookupComponent(components, module, { name, index, length }, wrapper) {
const scanInExports = () => this.lookupComponentInExports(components, { name, index, length }, module, wrapper);
async lookupComponent(components, module, dependencyContext, wrapper) {
const { name } = dependencyContext;
const scanInExports = () => this.lookupComponentInExports(components, dependencyContext, module, wrapper);
return components.has(name) ? components.get(name) : await scanInExports();
}
async lookupComponentInExports(components, { name, index, length }, module, wrapper) {
const instanceWrapper = await this.lookupComponentInRelatedModules(module, name);
async lookupComponentInExports(components, dependencyContext, module, wrapper) {
const instanceWrapper = await this.lookupComponentInRelatedModules(module, dependencyContext.name);
if (shared_utils_1.isNil(instanceWrapper)) {
throw new unknown_dependencies_exception_1.UnknownDependenciesException(wrapper.name, index, length);
throw new unknown_dependencies_exception_1.UnknownDependenciesException(wrapper.name, dependencyContext);
}
return instanceWrapper;
}
Expand Down
7 changes: 4 additions & 3 deletions bundle/core/injector/module.js
Expand Up @@ -214,12 +214,13 @@ class Module {
if (this._components.has(token)) {
return token;
}
const relatedModules = [...this._relatedModules.values()];
const modulesTokens = relatedModules
const importedArray = [...this._relatedModules.values()];
const importedRefNames = importedArray
.filter(item => item)
.map(({ metatype }) => metatype)
.filter(metatype => metatype)
.map(({ name }) => name);
if (modulesTokens.indexOf(token) < 0) {
if (importedRefNames.indexOf(token) < 0) {
const { name } = this.metatype;
throw new unknown_export_exception_1.UnknownExportException(name);
}
Expand Down
6 changes: 2 additions & 4 deletions bundle/core/nest-factory.d.ts
Expand Up @@ -12,11 +12,9 @@ export declare class NestFactoryStatic {
* Creates an instance of the NestApplication
* @returns {Promise}
*/
create(module: any): Promise<INestApplication & INestExpressApplication>;
create(module: any, options: NestApplicationOptions): Promise<INestApplication & INestExpressApplication>;
create(module: any, options?: NestApplicationOptions): Promise<INestApplication & INestExpressApplication>;
create(module: any, httpServer: FastifyAdapter, options?: NestApplicationOptions): Promise<INestApplication & INestFastifyApplication>;
create(module: any, httpServer: HttpServer, options?: NestApplicationOptions): Promise<INestApplication & INestExpressApplication>;
create(module: any, httpServer: any, options?: NestApplicationOptions): Promise<INestApplication & INestExpressApplication>;
create(module: any, httpServer: HttpServer | any, options?: NestApplicationOptions): Promise<INestApplication & INestExpressApplication>;
/**
* Creates an instance of the NestMicroservice
*
Expand Down
1 change: 1 addition & 0 deletions bundle/core/scanner.d.ts
Expand Up @@ -36,4 +36,5 @@ export declare class DependenciesScanner {
getApplyProvidersMap(): {
[type: string]: Function;
};
isDynamicModule(module: Type<any> | DynamicModule): module is DynamicModule;
}
15 changes: 11 additions & 4 deletions bundle/core/scanner.js
@@ -1,6 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const constants_1 = require("@nestjs/common/constants");
const random_string_generator_util_1 = require("@nestjs/common/utils/random-string-generator.util");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
require("reflect-metadata");
const application_config_1 = require("./application-config");
Expand All @@ -20,7 +21,12 @@ class DependenciesScanner {
}
async scanForModules(module, scope = []) {
await this.storeModule(module, scope);
const modules = this.reflectMetadata(module, constants_1.metadata.MODULES);
const modules = !this.isDynamicModule(module)
? this.reflectMetadata(module, constants_1.metadata.MODULES)
: [
...this.reflectMetadata(module.module, constants_1.metadata.MODULES),
...(module.imports || []),
];
for (const innerModule of modules) {
await this.scanForModules(innerModule, [].concat(scope, module));
}
Expand Down Expand Up @@ -136,9 +142,7 @@ class DependenciesScanner {
if (providersKeys.indexOf(type) < 0) {
return this.container.addComponent(component, token);
}
const providerToken = Math.random()
.toString(36)
.substring(2, 32);
const providerToken = random_string_generator_util_1.randomStringGenerator();
this.applicationProvidersApplyMap.push({
type,
moduleKey: token,
Expand Down Expand Up @@ -175,5 +179,8 @@ class DependenciesScanner {
[constants_2.APP_FILTER]: filter => this.applicationConfig.addGlobalFilter(filter),
};
}
isDynamicModule(module) {
return module && !!module.module;
}
}
exports.DependenciesScanner = DependenciesScanner;
46 changes: 21 additions & 25 deletions gulpfile.js
Expand Up @@ -2,7 +2,6 @@ const fs = require('fs');
const path = require('path');
const gulp = require('gulp');
const ts = require('gulp-typescript');
const gulpSequence = require('gulp-sequence');
const sourcemaps = require('gulp-sourcemaps');
const clean = require('gulp-clean');

Expand All @@ -22,18 +21,18 @@ gulp.task('default', function() {
modules.forEach(module => {
gulp.watch(
[`${source}/${module}/**/*.ts`, `${source}/${module}/*.ts`],
[module]
[module],
);
});
});

gulp.task('copy:ts', function() {
return gulp.packages(['packages/**/*.ts']).pipe(gulp.dest('./bundle'));
return gulp.src(['packages/**/*.ts']).pipe(gulp.dest('./bundle'));
});


gulp.task('copy-docs', function() {
return gulp.src('Readme.md')
return gulp
.src('Readme.md')
.pipe(gulp.dest('bundle/common'))
.pipe(gulp.dest('bundle/core'))
.pipe(gulp.dest('bundle/microservices'))
Expand All @@ -43,7 +42,9 @@ gulp.task('copy-docs', function() {

gulp.task('clean:bundle', function() {
return gulp
.packages(['bundle/**/*.js.map', 'bundle/**/*.ts', '!bundle/**/*.d.ts'], { read: false })
.src(['bundle/**/*.js.map', 'bundle/**/*.ts', '!bundle/**/*.d.ts'], {
read: false,
})
.pipe(clean());
});

Expand All @@ -63,45 +64,40 @@ modules.forEach(module => {
.pipe(sourcemaps.init())
.pipe(packages[module]())
.pipe(
sourcemaps.mapSources(sourcePath => './' + sourcePath.split('/').pop())
sourcemaps.mapSources(sourcePath => './' + sourcePath.split('/').pop()),
)
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(`${dist}/${module}`));
});
});

gulp.task('build', function(cb) {
gulpSequence('common', modules.filter(module => module !== 'common'), cb);
});
gulp.task('common', gulp.series(modules));

gulp.task('build:dev', function(cb) {
gulpSequence(
'common:dev',
modules
.filter(module => module !== 'common')
.map(module => module + ':dev'),
'copy:ts',
cb
);
});
gulp.task(
'common:dev',
gulp.series(modules.map(module => module + ':dev'), 'copy:ts'),
);

gulp.task('build', gulp.series('common'));

gulp.task('build:dev', gulp.series('common:dev'));

function getFolders(dir) {
return fs.readdirSync(dir).filter(function(file) {
return fs.statSync(path.join(dir, file)).isDirectory();
});
}
gulp.task('move', function() {
const getDirs = (base) => getFolders(base)
.map((path) => `${base}/${path}`);
const getDirs = base => getFolders(base).map(path => `${base}/${path}`);

const examplesDirs = getDirs('sample');
const integrationDirs = getDirs('integration');
const directories = examplesDirs.concat(integrationDirs);

let stream = gulp
.src(['node_modules/@nestjs/**/*']);
let stream = gulp.src(['node_modules/@nestjs/**/*']);

directories.forEach((dir) => {
directories.forEach(dir => {
stream = stream.pipe(gulp.dest(dir + '/node_modules/@nestjs'));
});
return stream;
});

0 comments on commit f351f98

Please sign in to comment.