Merge branch 'update/version-5' of https://github.com/nestjs/nest into update/version-5

This commit is contained in:
Kamil Myśliwiec
2018-03-14 12:08:19 +01:00
103 changed files with 1600 additions and 3272 deletions

1
.gitignore vendored
View File

@@ -24,6 +24,7 @@ yarn-error.log
# tests
/test
/integration
/coverage
/.nyc_output
build/config\.gypi

View File

@@ -1,6 +1,13 @@
## 4.6.6
### Bug Fixes:
- **common**: `File(s)Interceptor` throws http status code 500 [#465](https://github.com/nestjs/nest/issues/437)
- **core**: e2e testing, `EXPRESS_REF` injector issue [#484](https://github.com/nestjs/nest/issues/484)
- **microservices**: `NO_PATTERN_MESSAGE` bugfix [#491](https://github.com/nestjs/nest/issues/491)
### Improvements:
- **common**: `class-transformer` update [#483](https://github.com/nestjs/nest/pull/483/)
- **common**: `HttpService` improvements, remove duplicated `axios` interfaces [#470](https://github.com/nestjs/nest/pull/470)
- **core**: far more meaningful exception when not available component is exported (module inconsistency) [#479](https://github.com/nestjs/nest/issues/479)
## 4.6.5
### Bug Fixes

View File

@@ -36,11 +36,16 @@
To check out the [guide](https://docs.nestjs.com), visit [docs.nestjs.com](https://docs.nestjs.com). :books:
## Sponsors
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://opencollective.com/nest).
<a href="https://valor-software.com/"><img src="https://docs.nestjs.com/assets/sponsors/valor-software.png" width="210" /></a> &nbsp; &nbsp; <a href="https://scal.io"><img src="https://nestjs.com/img/scalio-logo.png" width="160" /></a>
#### Principal Sponsor
<a href="https://valor-software.com/"><img src="https://docs.nestjs.com/assets/sponsors/valor-software.png" width="210" /></a>
#### Sponsors
<a href="https://scal.io"><img src="https://nestjs.com/img/scalio-logo.svg" width="160" /></a> &nbsp; <a href="https://www.swingdev.io"><img src="https://nestjs.com/img/swingdev-logo.svg#1" width="160" /></a>
## Backers
@@ -86,11 +91,14 @@ Nest is an MIT-licensed open source project. It can grow thanks to the sponsors
<a href="https://opencollective.com/nest/backer/39/website" target="_blank"><img src="https://opencollective.com/nest/backer/39/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/40/website" target="_blank"><img src="https://opencollective.com/nest/backer/40/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/41/website" target="_blank"><img src="https://opencollective.com/nest/backer/41/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/42/website" target="_blank"><img src="https://opencollective.com/nest/backer/42/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/43/website" target="_blank"><img src="https://opencollective.com/nest/backer/43/avatar.svg"></a>
## People
## Stay in touch
- Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License

View File

@@ -1,8 +1,8 @@
import { Injectable, NestMiddleware, ExpressMiddleware } from '@nestjs/common';
import { Injectable, NestMiddleware, FunctionMiddleware } from '@nestjs/common';
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
resolve(context: string): ExpressMiddleware {
resolve(context: string): FunctionMiddleware {
return (req, res, next) => {
console.log(`[${context}] Request...`);
next();

View File

@@ -1,9 +1,11 @@
import { NestFactory } from '@nestjs/core';
import { ApplicationModule } from './app.module';
import { ValidationPipe } from './common/pipes/validation.pipe';
import { FastifyAdapter } from '@nestjs/core/adapters/fastify-adapter';
import * as fastify from 'fastify';
async function bootstrap() {
const app = await NestFactory.create(ApplicationModule);
const app = await NestFactory.create(ApplicationModule, new FastifyAdapter(fastify()));
app.useGlobalPipes(new ValidationPipe());
await app.listen(3000);
}

View File

@@ -1,5 +1,11 @@
import { Injectable, UseGuards } from '@nestjs/common';
import { Query, Mutation, Resolver, DelegateProperty, Subscription } from '@nestjs/graphql';
import {
Query,
Mutation,
Resolver,
DelegateProperty,
Subscription,
} from '@nestjs/graphql';
import { PubSub } from 'graphql-subscriptions';
import { Cat } from './interfaces/cat.interface';

View File

@@ -5,7 +5,7 @@ import { Cat } from './interfaces/cat.interface';
export class CatsService {
private readonly cats: Cat[] = [{ id: 1, name: 'Cat', age: 5 }];
create(cat: Cat): Cat{
create(cat: Cat): Cat {
this.cats.push(cat);
return cat;
}

View File

@@ -1 +1 @@
export const SUBSCRIPTION_SERVER = 'SUBSCRIPTION_SERVER';
export const SUBSCRIPTION_SERVER = 'SUBSCRIPTION_SERVER';

View File

@@ -7,9 +7,7 @@ export const createSubscriptionProviders = (port: number = 3001) => [
provide: SUBSCRIPTION_SERVER,
useFactory: () => {
const server = createServer();
return new Promise(resolve =>
server.listen(port, () => resolve(server)),
);
return new Promise(resolve => server.listen(port, () => resolve(server)));
},
},
];

View File

@@ -1,13 +1,17 @@
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');
const packages = {
common: ts.createProject('src/common/tsconfig.json'),
core: ts.createProject('src/core/tsconfig.json'),
microservices: ts.createProject('src/microservices/tsconfig.json'),
websockets: ts.createProject('src/websockets/tsconfig.json'),
testing: ts.createProject('src/testing/tsconfig.json'),
common: ts.createProject('src/common/tsconfig.json'),
core: ts.createProject('src/core/tsconfig.json'),
microservices: ts.createProject('src/microservices/tsconfig.json'),
websockets: ts.createProject('src/websockets/tsconfig.json'),
testing: ts.createProject('src/testing/tsconfig.json'),
};
const modules = Object.keys(packages);
const source = 'src';
@@ -15,51 +19,79 @@ const distId = process.argv.indexOf('--dist');
const dist = distId < 0 ? 'node_modules/@nestjs' : process.argv[distId + 1];
gulp.task('default', function() {
modules.forEach(module => {
gulp.watch(
[`${source}/${module}/**/*.ts`, `${source}/${module}/*.ts`],
[module]
);
});
modules.forEach(module => {
gulp.watch(
[`${source}/${module}/**/*.ts`, `${source}/${module}/*.ts`],
[module]
);
});
});
gulp.task('copy:ts', function() {
return gulp.src(['src/**/*.ts']).pipe(gulp.dest('./lib'));
});
gulp.task('clean:lib', function() {
return gulp
.src(['lib/**/*.js.map', 'lib/**/*.ts', '!lib/**/*.d.ts'], { read: false })
.pipe(clean());
});
modules.forEach(module => {
gulp.task(module, () => {
return packages[module]
.src()
.pipe(packages[module]())
.pipe(gulp.dest(`${dist}/${module}`));
});
gulp.task(module, () => {
return packages[module]
.src()
.pipe(packages[module]())
.pipe(gulp.dest(`${dist}/${module}`));
});
});
modules.forEach(module => {
gulp.task(module + ':dev', () => {
return packages[module]
.src()
.pipe(sourcemaps.init())
.pipe(packages[module]())
.pipe(
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);
gulpSequence('common', modules.filter(module => module !== 'common'), cb);
});
gulp.task('move', function() {
gulp.src(['node_modules/@nestjs/**/*']).pipe(
gulp.dest('examples/01-cats-app/node_modules/@nestjs')
).pipe(
gulp.dest('examples/02-gateways/node_modules/@nestjs')
).pipe(
gulp.dest('examples/03-microservices/node_modules/@nestjs')
).pipe(
gulp.dest('examples/04-injector/node_modules/@nestjs')
).pipe(
gulp.dest('examples/05-sql-typeorm/node_modules/@nestjs')
).pipe(
gulp.dest('examples/06-mongoose/node_modules/@nestjs')
).pipe(
gulp.dest('examples/07-sequelize/node_modules/@nestjs')
).pipe(
gulp.dest('examples/08-passport/node_modules/@nestjs')
).pipe(
gulp.dest('examples/09-babel-example/node_modules/@nestjs')
).pipe(
gulp.dest('examples/11-swagger/node_modules/@nestjs')
).pipe(
gulp.dest('examples/12-graphql-apollo/node_modules/@nestjs')
).pipe(
gulp.dest('examples/15-mvc/node_modules/@nestjs')
gulp.task('build:dev', function(cb) {
gulpSequence(
'common:dev',
modules
.filter(module => module !== 'common')
.map(module => module + ':dev'),
'copy:ts',
cb
);
});
});
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 examplesDirs = getDirs('examples');
const integrationDirs = getDirs('integration');
const directories = examplesDirs.concat(integrationDirs);
let stream = gulp
.src(['node_modules/@nestjs/**/*']);
directories.forEach((dir) => {
stream = stream.pipe(gulp.dest(dir + '/node_modules/@nestjs'));
});
});

View File

@@ -3,5 +3,5 @@
"packages": [
"lib/*"
],
"version": "4.6.5"
"version": "4.6.6"
}

View File

@@ -7,14 +7,14 @@
[linux-image]: https://img.shields.io/travis/nestjs/nest/master.svg?label=linux
[linux-url]: https://travis-ci.org/nestjs/nest
<p align="center">A progressive <a href="http://nodejs.org" target="blank">Node.js</a> framework for building efficient and scalable web applications, heavily inspired by <a href="https://angular.io" target="blank">Angular</a>.</p>
<p align="center">A progressive <a href="http://nodejs.org" target="blank">Node.js</a> framework for building efficient and scalable server-side applications, heavily inspired by <a href="https://angular.io" target="blank">Angular</a>.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/dm/@nestjs/core.svg" alt="NPM Downloads" /></a>
<a href="https://travis-ci.org/nestjs/nest"><img src="https://api.travis-ci.org/nestjs/nest.svg?branch=master" alt="Travis" /></a>
<a href="https://travis-ci.org/nestjs/nest"><img src="https://img.shields.io/travis/nestjs/nest/master.svg?label=linux" alt="Linux" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#4" alt="Coverage" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#5" alt="Coverage" /></a>
<a href="https://gitter.im/nestjs/nestjs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=body_badge"><img src="https://badges.gitter.im/nestjs/nestjs.svg" alt="Gitter" /></a>
<a href="https://opencollective.com/nest#backer"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
@@ -24,7 +24,7 @@
## Description
<p>Nest is a framework for building efficient, scalable <a href="http://nodejs.org" target="_blank">Node.js</a> web applications. It uses modern JavaScript, is built with <a href="http://www.typescriptlang.org" target="_blank">TypeScript</a> (preserves compatibility with pure JavaScript) and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).</p>
<p>Nest is a framework for building efficient, scalable <a href="http://nodejs.org" target="_blank">Node.js</a> server-side applications. It uses modern JavaScript, is built with <a href="http://www.typescriptlang.org" target="_blank">TypeScript</a> (preserves compatibility with pure JavaScript) and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).</p>
<p>Under the hood, Nest makes use of <a href="https://expressjs.com/" target="_blank">Express</a>, allowing for easy use of the myriad third-party plugins which are available.</p>
## Philosophy
@@ -36,11 +36,16 @@
To check out the [guide](https://docs.nestjs.com), visit [docs.nestjs.com](https://docs.nestjs.com). :books:
## Sponsors
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://opencollective.com/nest). Thanks! :heart_eyes:
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://opencollective.com/nest).
<a href="https://valor-software.com/"><img src="https://docs.nestjs.com/assets/sponsors/valor-software.png" width="210" /></a>
#### Principal Sponsor
<a href="https://valor-software.com/"><img src="https://docs.nestjs.com/assets/sponsors/valor-software.png" width="210" /></a>
#### Sponsors
<a href="https://scal.io"><img src="https://nestjs.com/img/scalio-logo.svg" width="160" /></a> &nbsp; <a href="https://www.swingdev.io"><img src="https://nestjs.com/img/swingdev-logo.svg#1" width="160" /></a>
## Backers
@@ -74,12 +79,29 @@ Nest is an MIT-licensed open source project. It can grow thanks to the sponsors
<a href="https://opencollective.com/nest/backer/27/website" target="_blank"><img src="https://opencollective.com/nest/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/28/website" target="_blank"><img src="https://opencollective.com/nest/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/29/website" target="_blank"><img src="https://opencollective.com/nest/backer/29/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/30/website" target="_blank"><img src="https://opencollective.com/nest/backer/30/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/31/website" target="_blank"><img src="https://opencollective.com/nest/backer/31/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/32/website" target="_blank"><img src="https://opencollective.com/nest/backer/32/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/33/website" target="_blank"><img src="https://opencollective.com/nest/backer/33/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/34/website" target="_blank"><img src="https://opencollective.com/nest/backer/34/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/35/website" target="_blank"><img src="https://opencollective.com/nest/backer/35/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/36/website" target="_blank"><img src="https://opencollective.com/nest/backer/36/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/37/website" target="_blank"><img src="https://opencollective.com/nest/backer/37/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/38/website" target="_blank"><img src="https://opencollective.com/nest/backer/38/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/39/website" target="_blank"><img src="https://opencollective.com/nest/backer/39/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/40/website" target="_blank"><img src="https://opencollective.com/nest/backer/40/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/41/website" target="_blank"><img src="https://opencollective.com/nest/backer/41/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/42/website" target="_blank"><img src="https://opencollective.com/nest/backer/42/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/43/website" target="_blank"><img src="https://opencollective.com/nest/backer/43/avatar.svg"></a>
## People
## Stay in touch
- Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](LICENSE).
<h4 align="center"> <a href="readme_zh.md">中文说明</a></h4>

View File

@@ -1,11 +1,16 @@
import { AxiosRequestConfig, AxiosResponse } from 'axios';
import { Observable } from 'rxjs/Observable';
<<<<<<< HEAD
import { AxiosRequestConfig, AxiosResponse } from './interfaces/axios.interfaces';
=======
import 'rxjs/add/observable/fromPromise';
>>>>>>> master
export declare class HttpService {
request<T = any>(config: AxiosRequestConfig): Observable<AxiosResponse<T>>;
get<T = any>(url: string, config?: AxiosRequestConfig): Observable<AxiosResponse<T>>;
delete(url: string, config?: AxiosRequestConfig): Observable<AxiosResponse<any>>;
head(url: string, config?: AxiosRequestConfig): Observable<AxiosResponse<any>>;
post(url: string, data?: any, config?: AxiosRequestConfig): Observable<AxiosResponse<any>>;
put(url: string, data?: any, config?: AxiosRequestConfig): Observable<AxiosResponse<any>>;
patch(url: string, data?: any, config?: AxiosRequestConfig): Observable<AxiosResponse<any>>;
delete<T = any>(url: string, config?: AxiosRequestConfig): Observable<AxiosResponse<T>>;
head<T = any>(url: string, config?: AxiosRequestConfig): Observable<AxiosResponse<T>>;
post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Observable<AxiosResponse<T>>;
put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Observable<AxiosResponse<T>>;
patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Observable<AxiosResponse<T>>;
}

View File

@@ -1,109 +1,123 @@
export interface AxiosTransformer {
(data: any, headers?: any): any;
(data: any, headers?: any): any;
}
export interface AxiosAdapter {
(config: AxiosRequestConfig): AxiosPromise<any>;
(config: AxiosRequestConfig): AxiosPromise<any>;
}
export interface AxiosBasicCredentials {
username: string;
password: string;
username: string;
password: string;
}
export interface AxiosProxyConfig {
host: string;
port: number;
host: string;
port: number;
}
export interface AxiosRequestConfig {
url?: string;
method?: string;
baseURL?: string;
transformRequest?: AxiosTransformer | AxiosTransformer[];
transformResponse?: AxiosTransformer | AxiosTransformer[];
headers?: any;
params?: any;
paramsSerializer?: (params: any) => string;
data?: any;
timeout?: number;
withCredentials?: boolean;
adapter?: AxiosAdapter;
auth?: AxiosBasicCredentials;
responseType?: string;
xsrfCookieName?: string;
xsrfHeaderName?: string;
onUploadProgress?: (progressEvent: any) => void;
onDownloadProgress?: (progressEvent: any) => void;
maxContentLength?: number;
validateStatus?: (status: number) => boolean;
maxRedirects?: number;
httpAgent?: any;
httpsAgent?: any;
proxy?: AxiosProxyConfig;
cancelToken?: CancelToken;
url?: string;
method?: string;
baseURL?: string;
transformRequest?: AxiosTransformer | AxiosTransformer[];
transformResponse?: AxiosTransformer | AxiosTransformer[];
headers?: any;
params?: any;
paramsSerializer?: (params: any) => string;
data?: any;
timeout?: number;
withCredentials?: boolean;
adapter?: AxiosAdapter;
auth?: AxiosBasicCredentials;
responseType?: string;
xsrfCookieName?: string;
xsrfHeaderName?: string;
onUploadProgress?: (progressEvent: any) => void;
onDownloadProgress?: (progressEvent: any) => void;
maxContentLength?: number;
validateStatus?: (status: number) => boolean;
maxRedirects?: number;
httpAgent?: any;
httpsAgent?: any;
proxy?: AxiosProxyConfig;
cancelToken?: CancelToken;
}
export interface AxiosResponse<T = any> {
data: T;
status: number;
statusText: string;
headers: any;
config: AxiosRequestConfig;
request?: any;
data: T;
status: number;
statusText: string;
headers: any;
config: AxiosRequestConfig;
request?: any;
}
export interface AxiosError extends Error {
config: AxiosRequestConfig;
code?: string;
request?: any;
response?: AxiosResponse;
}
export interface AxiosPromise<T = any> extends Promise<AxiosResponse<T>> {
config: AxiosRequestConfig;
code?: string;
request?: any;
response?: AxiosResponse;
}
export interface AxiosPromise<T = any> extends Promise<AxiosResponse<T>> {}
export interface CancelStatic {
new (message?: string): Cancel;
new (message?: string): Cancel;
}
export interface Cancel {
message: string;
message: string;
}
export interface Canceler {
(message?: string): void;
(message?: string): void;
}
export interface CancelTokenStatic {
new (executor: (cancel: Canceler) => void): CancelToken;
source(): CancelTokenSource;
new (executor: (cancel: Canceler) => void): CancelToken;
source(): CancelTokenSource;
}
export interface CancelToken {
promise: Promise<Cancel>;
reason?: Cancel;
throwIfRequested(): void;
promise: Promise<Cancel>;
reason?: Cancel;
throwIfRequested(): void;
}
export interface CancelTokenSource {
token: CancelToken;
cancel: Canceler;
token: CancelToken;
cancel: Canceler;
}
export interface AxiosInterceptorManager<V> {
use(onFulfilled?: (value: V) => V | Promise<V>, onRejected?: (error: any) => any): number;
eject(id: number): void;
use(
onFulfilled?: (value: V) => V | Promise<V>,
onRejected?: (error: any) => any,
): number;
eject(id: number): void;
}
export interface AxiosInstance {
defaults: AxiosRequestConfig;
interceptors: {
request: AxiosInterceptorManager<AxiosRequestConfig>;
response: AxiosInterceptorManager<AxiosResponse>;
};
request<T = any>(config: AxiosRequestConfig): AxiosPromise<T>;
get<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>;
delete(url: string, config?: AxiosRequestConfig): AxiosPromise;
head(url: string, config?: AxiosRequestConfig): AxiosPromise;
post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>;
put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>;
patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>;
defaults: AxiosRequestConfig;
interceptors: {
request: AxiosInterceptorManager<AxiosRequestConfig>;
response: AxiosInterceptorManager<AxiosResponse>;
};
request<T = any>(config: AxiosRequestConfig): AxiosPromise<T>;
get<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>;
delete(url: string, config?: AxiosRequestConfig): AxiosPromise;
head(url: string, config?: AxiosRequestConfig): AxiosPromise;
post<T = any>(
url: string,
data?: any,
config?: AxiosRequestConfig,
): AxiosPromise<T>;
put<T = any>(
url: string,
data?: any,
config?: AxiosRequestConfig,
): AxiosPromise<T>;
patch<T = any>(
url: string,
data?: any,
config?: AxiosRequestConfig,
): AxiosPromise<T>;
}
export interface AxiosStatic extends AxiosInstance {
(config: AxiosRequestConfig): AxiosPromise;
(url: string, config?: AxiosRequestConfig): AxiosPromise;
create(config?: AxiosRequestConfig): AxiosInstance;
Cancel: CancelStatic;
CancelToken: CancelTokenStatic;
isCancel(value: any): boolean;
all<T>(values: (T | Promise<T>)[]): Promise<T[]>;
spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
(config: AxiosRequestConfig): AxiosPromise;
(url: string, config?: AxiosRequestConfig): AxiosPromise;
create(config?: AxiosRequestConfig): AxiosInstance;
Cancel: CancelStatic;
CancelToken: CancelTokenStatic;
isCancel(value: any): boolean;
all<T>(values: (T | Promise<T>)[]): Promise<T[]>;
spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
}
declare const Axios: AxiosStatic;
export default Axios;

View File

@@ -10,6 +10,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
Object.defineProperty(exports, "__esModule", { value: true });
const multer = require("multer");
const component_decorator_1 = require("../decorators/core/component.decorator");
const multer_utils_1 = require("./multer/multer.utils");
function FileInterceptor(fieldName, options) {
return component_decorator_1.mixin(class {
constructor() {
@@ -19,7 +20,8 @@ function FileInterceptor(fieldName, options) {
return __awaiter(this, void 0, void 0, function* () {
yield new Promise((resolve, reject) => this.upload.single(fieldName)(request, request.res, err => {
if (err) {
return reject(err);
const error = multer_utils_1.transformException(err);
return reject(error);
}
resolve();
}));

View File

@@ -9,6 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
};
Object.defineProperty(exports, "__esModule", { value: true });
const multer = require("multer");
const multer_utils_1 = require("./multer/multer.utils");
function FilesInterceptor(fieldName, maxCount, options) {
const Interceptor = class {
constructor() {
@@ -18,7 +19,8 @@ function FilesInterceptor(fieldName, maxCount, options) {
return __awaiter(this, void 0, void 0, function* () {
yield new Promise((resolve, reject) => this.upload.array(fieldName, maxCount)(request, request.res, err => {
if (err) {
return reject(err);
const error = multer_utils_1.transformException(err);
return reject(error);
}
resolve();
}));

View File

@@ -0,0 +1,9 @@
export declare const multerExceptions: {
LIMIT_PART_COUNT: string;
LIMIT_FILE_SIZE: string;
LIMIT_FILE_COUNT: string;
LIMIT_FIELD_KEY: string;
LIMIT_FIELD_VALUE: string;
LIMIT_FIELD_COUNT: string;
LIMIT_UNEXPECTED_FILE: string;
};

View File

@@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.multerExceptions = {
LIMIT_PART_COUNT: 'Too many parts',
LIMIT_FILE_SIZE: 'File too large',
LIMIT_FILE_COUNT: 'Too many files',
LIMIT_FIELD_KEY: 'Field name too long',
LIMIT_FIELD_VALUE: 'Field value too long',
LIMIT_FIELD_COUNT: 'Too many fields',
LIMIT_UNEXPECTED_FILE: 'Unexpected field',
};

View File

@@ -0,0 +1,2 @@
import { BadRequestException } from './../../exceptions';
export declare function transformException(error: Error | undefined): Error | BadRequestException;

View File

@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const exceptions_1 = require("./../../exceptions");
const multer_constants_1 = require("./multer.constants");
function transformException(error) {
if (!error || error instanceof exceptions_1.HttpException) {
return error;
}
switch (error.message) {
case multer_constants_1.multerExceptions.LIMIT_FILE_SIZE:
return new exceptions_1.PayloadTooLargeException(error.message);
case multer_constants_1.multerExceptions.LIMIT_FILE_COUNT:
case multer_constants_1.multerExceptions.LIMIT_FIELD_KEY:
case multer_constants_1.multerExceptions.LIMIT_FIELD_VALUE:
case multer_constants_1.multerExceptions.LIMIT_FIELD_COUNT:
case multer_constants_1.multerExceptions.LIMIT_UNEXPECTED_FILE:
case multer_constants_1.multerExceptions.LIMIT_PART_COUNT:
return new exceptions_1.BadRequestException(error.message);
}
return error;
}
exports.transformException = transformException;

View File

@@ -0,0 +1,11 @@
export declare type CustomOrigin = (requestOrigin: string, callback: (err: Error | null, allow?: boolean) => void) => void;
export interface CorsOptions {
origin?: boolean | string | RegExp | (string | RegExp)[] | CustomOrigin;
methods?: string | string[];
allowedHeaders?: string | string[];
exposedHeaders?: string | string[];
credentials?: boolean;
maxAge?: number;
preflightContinue?: boolean;
optionsSuccessStatus?: number;
}

View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

View File

@@ -1,7 +1,8 @@
import { HttpsOptions } from './external/https-options.interface';
import { NestApplicationContextOptions } from './nest-application-context-options.interface';
import { CorsOptions } from './external/cors-options.interface';
export interface NestApplicationOptions extends NestApplicationContextOptions {
cors?: boolean;
cors?: boolean | CorsOptions;
bodyParser?: boolean;
httpsOptions?: HttpsOptions;
}

View File

@@ -3,6 +3,7 @@ import { WebSocketAdapter } from './websockets/web-socket-adapter.interface';
import { CanActivate } from './features/can-activate.interface';
import { NestInterceptor } from './features/nest-interceptor.interface';
import { INestApplicationContext } from './nest-application-context.interface';
import { CorsOptions } from './external/cors-options.interface';
export interface INestApplication extends INestApplicationContext {
/**
* Initializes application. It is not mandatory to call this method directly.
@@ -43,7 +44,7 @@ export interface INestApplication extends INestApplicationContext {
*
* @returns void
*/
enableCors(): this;
enableCors(options?: CorsOptions): this;
/**
* A wrapper function around native `express.disable()` method.
* Example `app.disable('x-powered-by')`

View File

@@ -1,17 +1,17 @@
{
"name": "@nestjs/common",
"version": "4.6.5",
"version": "4.6.6",
"description": "Nest - modern, fast, powerful node.js web framework (@common)",
"author": "Kamil Mysliwiec",
"license": "MIT",
"dependencies": {
"axios": "0.17.1",
"class-transformer": "0.1.8",
"class-transformer": "0.1.9",
"class-validator": "0.8.1",
"cli-color": "1.1.0",
"deprecate": "1.0.0"
},
"peerDependencies": {
"reflect-metadata": "0.1.10"
"reflect-metadata": "0.1.12"
}
}

View File

@@ -51,7 +51,9 @@ let ValidationPipe = class ValidationPipe {
}
return this.isTransformEnabled
? entity
: Object.keys(this.validatorOptions).length > 0 ? class_transformer_1.classToPlain(entity) : value;
: Object.keys(this.validatorOptions).length > 0
? class_transformer_1.classToPlain(entity)
: value;
});
}
toValidate(metadata) {

View File

@@ -5,5 +5,4 @@ export declare const createHttpExceptionBody: (message: any, error: string, stat
} | {
statusCode: number;
error: string;
message?: undefined;
};

View File

@@ -1,5 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createHttpExceptionBody = (message, error, statusCode) => message
? { statusCode, error, message }
: { statusCode, error };
exports.createHttpExceptionBody = (message, error, statusCode) => (message ? { statusCode, error, message } : { statusCode, error });

View File

@@ -7,14 +7,14 @@
[linux-image]: https://img.shields.io/travis/nestjs/nest/master.svg?label=linux
[linux-url]: https://travis-ci.org/nestjs/nest
<p align="center">A progressive <a href="http://nodejs.org" target="blank">Node.js</a> framework for building efficient and scalable web applications, heavily inspired by <a href="https://angular.io" target="blank">Angular</a>.</p>
<p align="center">A progressive <a href="http://nodejs.org" target="blank">Node.js</a> framework for building efficient and scalable server-side applications, heavily inspired by <a href="https://angular.io" target="blank">Angular</a>.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/dm/@nestjs/core.svg" alt="NPM Downloads" /></a>
<a href="https://travis-ci.org/nestjs/nest"><img src="https://api.travis-ci.org/nestjs/nest.svg?branch=master" alt="Travis" /></a>
<a href="https://travis-ci.org/nestjs/nest"><img src="https://img.shields.io/travis/nestjs/nest/master.svg?label=linux" alt="Linux" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#4" alt="Coverage" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#5" alt="Coverage" /></a>
<a href="https://gitter.im/nestjs/nestjs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=body_badge"><img src="https://badges.gitter.im/nestjs/nestjs.svg" alt="Gitter" /></a>
<a href="https://opencollective.com/nest#backer"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
@@ -24,7 +24,7 @@
## Description
<p>Nest is a framework for building efficient, scalable <a href="http://nodejs.org" target="_blank">Node.js</a> web applications. It uses modern JavaScript, is built with <a href="http://www.typescriptlang.org" target="_blank">TypeScript</a> (preserves compatibility with pure JavaScript) and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).</p>
<p>Nest is a framework for building efficient, scalable <a href="http://nodejs.org" target="_blank">Node.js</a> server-side applications. It uses modern JavaScript, is built with <a href="http://www.typescriptlang.org" target="_blank">TypeScript</a> (preserves compatibility with pure JavaScript) and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).</p>
<p>Under the hood, Nest makes use of <a href="https://expressjs.com/" target="_blank">Express</a>, allowing for easy use of the myriad third-party plugins which are available.</p>
## Philosophy
@@ -36,11 +36,16 @@
To check out the [guide](https://docs.nestjs.com), visit [docs.nestjs.com](https://docs.nestjs.com). :books:
## Sponsors
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://opencollective.com/nest). Thanks! :heart_eyes:
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://opencollective.com/nest).
<a href="https://valor-software.com/"><img src="https://docs.nestjs.com/assets/sponsors/valor-software.png" width="210" /></a>
#### Principal Sponsor
<a href="https://valor-software.com/"><img src="https://docs.nestjs.com/assets/sponsors/valor-software.png" width="210" /></a>
#### Sponsors
<a href="https://scal.io"><img src="https://nestjs.com/img/scalio-logo.svg" width="160" /></a> &nbsp; <a href="https://www.swingdev.io"><img src="https://nestjs.com/img/swingdev-logo.svg#1" width="160" /></a>
## Backers
@@ -74,12 +79,29 @@ Nest is an MIT-licensed open source project. It can grow thanks to the sponsors
<a href="https://opencollective.com/nest/backer/27/website" target="_blank"><img src="https://opencollective.com/nest/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/28/website" target="_blank"><img src="https://opencollective.com/nest/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/29/website" target="_blank"><img src="https://opencollective.com/nest/backer/29/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/30/website" target="_blank"><img src="https://opencollective.com/nest/backer/30/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/31/website" target="_blank"><img src="https://opencollective.com/nest/backer/31/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/32/website" target="_blank"><img src="https://opencollective.com/nest/backer/32/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/33/website" target="_blank"><img src="https://opencollective.com/nest/backer/33/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/34/website" target="_blank"><img src="https://opencollective.com/nest/backer/34/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/35/website" target="_blank"><img src="https://opencollective.com/nest/backer/35/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/36/website" target="_blank"><img src="https://opencollective.com/nest/backer/36/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/37/website" target="_blank"><img src="https://opencollective.com/nest/backer/37/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/38/website" target="_blank"><img src="https://opencollective.com/nest/backer/38/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/39/website" target="_blank"><img src="https://opencollective.com/nest/backer/39/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/40/website" target="_blank"><img src="https://opencollective.com/nest/backer/40/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/41/website" target="_blank"><img src="https://opencollective.com/nest/backer/41/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/42/website" target="_blank"><img src="https://opencollective.com/nest/backer/42/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/43/website" target="_blank"><img src="https://opencollective.com/nest/backer/43/avatar.svg"></a>
## People
## Stay in touch
- Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](LICENSE).
<h4 align="center"> <a href="readme_zh.md">中文说明</a></h4>

View File

@@ -1,7 +1,7 @@
export declare const UnknownDependenciesMessage: (type: string, index: number, length: number) => string;
export declare const InvalidMiddlewareMessage: (name: string) => string;
export declare const InvalidModuleMessage: (scope: string) => string;
export declare const UnknownExportMessage: (name: string) => string;
export declare const UnknownExportMessage: (module: string) => string;
export declare const INVALID_MIDDLEWARE_CONFIGURATION = "Invalid middleware configuration passed inside the module 'configure()' method.";
export declare const UNKNOWN_REQUEST_MAPPING = "Request mapping properties not defined in the @RequestMapping() annotation!";
export declare const UNHANDLED_RUNTIME_EXCEPTION = "Unhandled Runtime Exception.";

View File

@@ -10,8 +10,8 @@ exports.UnknownDependenciesMessage = (type, index, length) => {
return message;
};
exports.InvalidMiddlewareMessage = (name) => `The middleware doesn't provide the 'resolve' method (${name})`;
exports.InvalidModuleMessage = (scope) => `Nest can't create the module instance. The frequent reason of this exception is the circular dependency between modules. Use forwardRef() to avoid it (read more https://docs.nestjs.com/advanced/circular-dependency). Scope [${scope}]`;
exports.UnknownExportMessage = (name) => `You are trying to export unknown component (${name}). Remember - your component should be listed both in exports and components arrays!`;
exports.InvalidModuleMessage = (scope) => `Nest cannot create the module instance. The frequent reason of this exception is the circular dependency between modules. Use forwardRef() to avoid it (read more https://docs.nestjs.com/advanced/circular-dependency). Scope [${scope}]`;
exports.UnknownExportMessage = (module) => `Nest cannot export component / module that is not a part of the currently proccessed module (${module}). Please verify whether each exported unit is available in this particular context.`;
exports.INVALID_MIDDLEWARE_CONFIGURATION = `Invalid middleware configuration passed inside the module 'configure()' method.`;
exports.UNKNOWN_REQUEST_MAPPING = `Request mapping properties not defined in the @RequestMapping() annotation!`;
exports.UNHANDLED_RUNTIME_EXCEPTION = `Unhandled Runtime Exception.`;

View File

@@ -222,7 +222,9 @@ class Injector {
flatMap(modules) {
return modules.concat.apply(modules, modules.map((module) => {
const { relatedModules, exports } = module;
return this.flatMap([...relatedModules.values()].filter(related => {
return this.flatMap([...relatedModules.values()]
.filter(related => !!related)
.filter(related => {
const { metatype } = related;
return exports.has(metatype.name);
}));

View File

@@ -54,7 +54,12 @@ export declare class Module {
addCustomFactory(component: CustomFactory, collection: Map<string, any>): void;
addExportedComponent(exportedComponent: ComponentMetatype | string | DynamicModule): Set<string>;
addCustomExportedComponent(exportedComponent: CustomFactory | CustomValue | CustomClass): Set<string>;
<<<<<<< HEAD
addRoute(route: Type<Controller>): void;
=======
validateExportedProvider(token: string): string;
addRoute(route: Metatype<Controller>): void;
>>>>>>> master
addRelatedModule(relatedModule: any): void;
replace(toReplace: any, options: any): string;
createModuleRefMetatype(components: any): {

View File

@@ -1,5 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const unknown_export_exception_1 = require("../errors/exceptions/unknown-export.exception");
const module_ref_1 = require("./module-ref");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const runtime_exception_1 = require("../errors/exceptions/runtime.exception");
@@ -88,7 +89,7 @@ class Module {
name: tokens_1.HTTP_SERVER_REF,
metatype: {},
isResolved: true,
instance: applicationRef,
instance: applicationRef || {},
});
}
addExternalContextCreator(container) {
@@ -189,24 +190,40 @@ class Module {
});
}
addExportedComponent(exportedComponent) {
const addExportedUnit = (token) => this._exports.add(this.validateExportedProvider(token));
if (this.isCustomProvider(exportedComponent)) {
return this.addCustomExportedComponent(exportedComponent);
}
else if (shared_utils_1.isString(exportedComponent)) {
return this._exports.add(exportedComponent);
return addExportedUnit(exportedComponent);
}
else if (this.isDynamicModule(exportedComponent)) {
const { module } = exportedComponent;
return this._exports.add(module.name);
return addExportedUnit(module.name);
}
this._exports.add(exportedComponent.name);
addExportedUnit(exportedComponent.name);
}
addCustomExportedComponent(exportedComponent) {
const provide = exportedComponent.provide;
if (shared_utils_1.isString(provide) || shared_utils_1.isSymbol(provide)) {
return this._exports.add(provide);
return this._exports.add(this.validateExportedProvider(provide));
}
this._exports.add(provide.name);
this._exports.add(this.validateExportedProvider(provide.name));
}
validateExportedProvider(token) {
if (this._components.has(token)) {
return token;
}
const relatedModules = [...this._relatedModules.values()];
const modulesTokens = relatedModules
.map(({ metatype }) => metatype)
.filter(metatype => !!metatype)
.map(({ name }) => name);
if (modulesTokens.indexOf(token) < 0) {
const { name } = this.metatype;
throw new unknown_export_exception_1.UnknownExportException(name);
}
return token;
}
addRoute(route) {
this._routes.set(route.name, {

View File

@@ -32,7 +32,11 @@ class InterceptorsConsumer {
};
}
transformDeffered(next) {
<<<<<<< HEAD
return fromPromise_1.fromPromise(next()).pipe(operators_1.switchMap(res => {
=======
return Observable_1.Observable.fromPromise(next()).switchMap(res => {
>>>>>>> master
const isDeffered = res instanceof Promise || res instanceof Observable_1.Observable;
return isDeffered ? res : Promise.resolve(res);
}));

View File

@@ -1,6 +1,6 @@
{
"name": "@nestjs/core",
"version": "4.6.5",
"version": "4.6.6",
"description": "Nest - modern, fast, powerful node.js web framework (@core)",
"author": "Kamil Mysliwiec",
"license": "MIT",
@@ -14,7 +14,7 @@
},
"peerDependencies": {
"@nestjs/common": "^5.*",
"reflect-metadata": "0.1.10",
"reflect-metadata": "0.1.12",
"rxjs": "^5.5.6"
}
}

View File

@@ -73,7 +73,7 @@ class RoutesResolver {
}
mapExternalException(err) {
switch (true) {
case (err instanceof SyntaxError):
case err instanceof SyntaxError:
return new common_1.BadRequestException(err.message);
default:
return err;

View File

@@ -7,14 +7,14 @@
[linux-image]: https://img.shields.io/travis/nestjs/nest/master.svg?label=linux
[linux-url]: https://travis-ci.org/nestjs/nest
<p align="center">A progressive <a href="http://nodejs.org" target="blank">Node.js</a> framework for building efficient and scalable web applications, heavily inspired by <a href="https://angular.io" target="blank">Angular</a>.</p>
<p align="center">A progressive <a href="http://nodejs.org" target="blank">Node.js</a> framework for building efficient and scalable server-side applications, heavily inspired by <a href="https://angular.io" target="blank">Angular</a>.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/dm/@nestjs/core.svg" alt="NPM Downloads" /></a>
<a href="https://travis-ci.org/nestjs/nest"><img src="https://api.travis-ci.org/nestjs/nest.svg?branch=master" alt="Travis" /></a>
<a href="https://travis-ci.org/nestjs/nest"><img src="https://img.shields.io/travis/nestjs/nest/master.svg?label=linux" alt="Linux" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#4" alt="Coverage" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#5" alt="Coverage" /></a>
<a href="https://gitter.im/nestjs/nestjs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=body_badge"><img src="https://badges.gitter.im/nestjs/nestjs.svg" alt="Gitter" /></a>
<a href="https://opencollective.com/nest#backer"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
@@ -24,7 +24,7 @@
## Description
<p>Nest is a framework for building efficient, scalable <a href="http://nodejs.org" target="_blank">Node.js</a> web applications. It uses modern JavaScript, is built with <a href="http://www.typescriptlang.org" target="_blank">TypeScript</a> (preserves compatibility with pure JavaScript) and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).</p>
<p>Nest is a framework for building efficient, scalable <a href="http://nodejs.org" target="_blank">Node.js</a> server-side applications. It uses modern JavaScript, is built with <a href="http://www.typescriptlang.org" target="_blank">TypeScript</a> (preserves compatibility with pure JavaScript) and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).</p>
<p>Under the hood, Nest makes use of <a href="https://expressjs.com/" target="_blank">Express</a>, allowing for easy use of the myriad third-party plugins which are available.</p>
## Philosophy
@@ -36,11 +36,16 @@
To check out the [guide](https://docs.nestjs.com), visit [docs.nestjs.com](https://docs.nestjs.com). :books:
## Sponsors
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://opencollective.com/nest). Thanks! :heart_eyes:
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://opencollective.com/nest).
<a href="https://valor-software.com/"><img src="https://docs.nestjs.com/assets/sponsors/valor-software.png" width="210" /></a>
#### Principal Sponsor
<a href="https://valor-software.com/"><img src="https://docs.nestjs.com/assets/sponsors/valor-software.png" width="210" /></a>
#### Sponsors
<a href="https://scal.io"><img src="https://nestjs.com/img/scalio-logo.svg" width="160" /></a> &nbsp; <a href="https://www.swingdev.io"><img src="https://nestjs.com/img/swingdev-logo.svg#1" width="160" /></a>
## Backers
@@ -74,12 +79,29 @@ Nest is an MIT-licensed open source project. It can grow thanks to the sponsors
<a href="https://opencollective.com/nest/backer/27/website" target="_blank"><img src="https://opencollective.com/nest/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/28/website" target="_blank"><img src="https://opencollective.com/nest/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/29/website" target="_blank"><img src="https://opencollective.com/nest/backer/29/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/30/website" target="_blank"><img src="https://opencollective.com/nest/backer/30/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/31/website" target="_blank"><img src="https://opencollective.com/nest/backer/31/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/32/website" target="_blank"><img src="https://opencollective.com/nest/backer/32/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/33/website" target="_blank"><img src="https://opencollective.com/nest/backer/33/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/34/website" target="_blank"><img src="https://opencollective.com/nest/backer/34/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/35/website" target="_blank"><img src="https://opencollective.com/nest/backer/35/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/36/website" target="_blank"><img src="https://opencollective.com/nest/backer/36/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/37/website" target="_blank"><img src="https://opencollective.com/nest/backer/37/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/38/website" target="_blank"><img src="https://opencollective.com/nest/backer/38/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/39/website" target="_blank"><img src="https://opencollective.com/nest/backer/39/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/40/website" target="_blank"><img src="https://opencollective.com/nest/backer/40/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/41/website" target="_blank"><img src="https://opencollective.com/nest/backer/41/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/42/website" target="_blank"><img src="https://opencollective.com/nest/backer/42/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/43/website" target="_blank"><img src="https://opencollective.com/nest/backer/43/avatar.svg"></a>
## People
## Stay in touch
- Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](LICENSE).
<h4 align="center"> <a href="readme_zh.md">中文说明</a></h4>

View File

@@ -19,10 +19,17 @@ class ClientRedis extends client_proxy_1.ClientProxy {
const pattern = JSON.stringify(msg.pattern);
const responseCallback = (channel, message) => {
const { err, response, disposed } = JSON.parse(message);
<<<<<<< HEAD
if (disposed) {
callback(null, null, true);
this.subClient.unsubscribe(this.getResPatternName(pattern));
this.subClient.removeListener(constants_1.MESSAGE_EVENT, responseCallback);
=======
if (disposed || err) {
callback(err, null, true);
this.sub.unsubscribe(this.getResPatternName(pattern));
this.sub.removeListener(MESSAGE_EVENT, responseCallback);
>>>>>>> master
return;
}
callback(err, response);

View File

@@ -8,10 +8,17 @@ export declare class ClientTCP extends ClientProxy {
private isConnected;
private socket;
constructor({port, host}: ClientMetadata);
<<<<<<< HEAD
init(callback: (...args) => any): Promise<JsonSocket>;
protected sendMessage(msg: any, callback: (...args) => any): Promise<void>;
handleResponse(socket: JsonSocket, callback: (...args) => any, buffer: any, context: Function): any;
createSocket(): JsonSocket;
=======
init(callback: (...args) => any): Promise<{}>;
protected sendSingleMessage(msg: any, callback: (...args) => any): Promise<void>;
handleResponse(socket: any, callback: (...args) => any, buffer: any): any;
createSocket(): any;
>>>>>>> master
close(): void;
bindEvents(socket: JsonSocket, callback: (...args) => any): void;
handleError(err: any, callback: (...args) => any): void;

View File

@@ -51,9 +51,15 @@ class ClientTCP extends client_proxy_1.ClientProxy {
}
handleResponse(socket, callback, buffer, context) {
const { err, response, disposed } = buffer;
<<<<<<< HEAD
if (disposed) {
callback(null, null, true);
return socket._socket.removeListener(constants_1.MESSAGE_EVENT, context);
=======
if (disposed || err) {
callback(err, null, true);
return socket.end();
>>>>>>> master
}
callback(err, response);
}

View File

@@ -46,8 +46,14 @@ class NestMicroservice extends nest_application_context_1.NestApplicationContext
: server_factory_1.ServerFactory.create(this.microserviceConfig);
this.selectContextModule();
}
<<<<<<< HEAD
registerModules() {
this.socketModule && this.socketModule.register(this.container, this.applicationConfig);
=======
setupModules() {
this.socketModule &&
this.socketModule.setup(this.container, this.applicationConfig);
>>>>>>> master
this.microservicesModule.setupClients(this.container);
this.registerListeners();
this.setIsInitialized(true);
@@ -83,7 +89,7 @@ class NestMicroservice extends nest_application_context_1.NestApplicationContext
}
listenAsync() {
return __awaiter(this, void 0, void 0, function* () {
return yield new Promise((resolve) => this.listen(resolve));
return yield new Promise(resolve => this.listen(resolve));
});
}
close() {

View File

@@ -1,6 +1,6 @@
{
"name": "@nestjs/microservices",
"version": "4.6.5",
"version": "4.6.6",
"description": "Nest - modern, fast, powerful node.js web framework (@microservices)",
"author": "Kamil Mysliwiec",
"license": "MIT",
@@ -13,7 +13,7 @@
"peerDependencies": {
"@nestjs/common": "^5.*",
"@nestjs/core": "^5.*",
"reflect-metadata": "0.1.10",
"reflect-metadata": "0.1.12",
"rxjs": "^5.5.6"
}
}

View File

@@ -53,8 +53,7 @@ class ServerRedis extends server_1.Server {
const publish = this.getPublisher(pub, pattern);
const status = 'error';
if (!this.messageHandlers[pattern]) {
publish({ status, error: constants_1.NO_PATTERN_MESSAGE });
return;
return publish({ status, err: constants_1.NO_PATTERN_MESSAGE });
}
const handler = this.messageHandlers[pattern];
const response$ = this.transformToObservable(yield handler(msg.data));

View File

@@ -15,8 +15,12 @@ export declare class ServerTCP extends Server implements CustomTransportStrategy
handleMessage(socket: any, msg: {
pattern: any;
data: {};
<<<<<<< HEAD
}): Promise<void>;
handleClose(): undefined | number | NodeJS.Timer;
=======
}): Promise<any>;
>>>>>>> master
private init();
private getSocketInstance(socket);
}

View File

@@ -38,8 +38,7 @@ class ServerTCP extends server_1.Server {
const pattern = JSON.stringify(msg.pattern);
const status = 'error';
if (!this.messageHandlers[pattern]) {
socket.sendMessage({ status, error: constants_1.NO_PATTERN_MESSAGE });
return;
return socket.sendMessage({ status, err: constants_1.NO_PATTERN_MESSAGE });
}
const handler = this.messageHandlers[pattern];
const response$ = this.transformToObservable(yield handler(msg.data));

View File

@@ -7,14 +7,14 @@
[linux-image]: https://img.shields.io/travis/nestjs/nest/master.svg?label=linux
[linux-url]: https://travis-ci.org/nestjs/nest
<p align="center">A progressive <a href="http://nodejs.org" target="blank">Node.js</a> framework for building efficient and scalable web applications, heavily inspired by <a href="https://angular.io" target="blank">Angular</a>.</p>
<p align="center">A progressive <a href="http://nodejs.org" target="blank">Node.js</a> framework for building efficient and scalable server-side applications, heavily inspired by <a href="https://angular.io" target="blank">Angular</a>.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/dm/@nestjs/core.svg" alt="NPM Downloads" /></a>
<a href="https://travis-ci.org/nestjs/nest"><img src="https://api.travis-ci.org/nestjs/nest.svg?branch=master" alt="Travis" /></a>
<a href="https://travis-ci.org/nestjs/nest"><img src="https://img.shields.io/travis/nestjs/nest/master.svg?label=linux" alt="Linux" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#4" alt="Coverage" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#5" alt="Coverage" /></a>
<a href="https://gitter.im/nestjs/nestjs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=body_badge"><img src="https://badges.gitter.im/nestjs/nestjs.svg" alt="Gitter" /></a>
<a href="https://opencollective.com/nest#backer"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
@@ -24,7 +24,7 @@
## Description
<p>Nest is a framework for building efficient, scalable <a href="http://nodejs.org" target="_blank">Node.js</a> web applications. It uses modern JavaScript, is built with <a href="http://www.typescriptlang.org" target="_blank">TypeScript</a> (preserves compatibility with pure JavaScript) and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).</p>
<p>Nest is a framework for building efficient, scalable <a href="http://nodejs.org" target="_blank">Node.js</a> server-side applications. It uses modern JavaScript, is built with <a href="http://www.typescriptlang.org" target="_blank">TypeScript</a> (preserves compatibility with pure JavaScript) and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).</p>
<p>Under the hood, Nest makes use of <a href="https://expressjs.com/" target="_blank">Express</a>, allowing for easy use of the myriad third-party plugins which are available.</p>
## Philosophy
@@ -36,11 +36,16 @@
To check out the [guide](https://docs.nestjs.com), visit [docs.nestjs.com](https://docs.nestjs.com). :books:
## Sponsors
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://opencollective.com/nest). Thanks! :heart_eyes:
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://opencollective.com/nest).
<a href="https://valor-software.com/"><img src="https://docs.nestjs.com/assets/sponsors/valor-software.png" width="210" /></a>
#### Principal Sponsor
<a href="https://valor-software.com/"><img src="https://docs.nestjs.com/assets/sponsors/valor-software.png" width="210" /></a>
#### Sponsors
<a href="https://scal.io"><img src="https://nestjs.com/img/scalio-logo.svg" width="160" /></a> &nbsp; <a href="https://www.swingdev.io"><img src="https://nestjs.com/img/swingdev-logo.svg#1" width="160" /></a>
## Backers
@@ -74,12 +79,29 @@ Nest is an MIT-licensed open source project. It can grow thanks to the sponsors
<a href="https://opencollective.com/nest/backer/27/website" target="_blank"><img src="https://opencollective.com/nest/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/28/website" target="_blank"><img src="https://opencollective.com/nest/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/29/website" target="_blank"><img src="https://opencollective.com/nest/backer/29/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/30/website" target="_blank"><img src="https://opencollective.com/nest/backer/30/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/31/website" target="_blank"><img src="https://opencollective.com/nest/backer/31/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/32/website" target="_blank"><img src="https://opencollective.com/nest/backer/32/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/33/website" target="_blank"><img src="https://opencollective.com/nest/backer/33/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/34/website" target="_blank"><img src="https://opencollective.com/nest/backer/34/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/35/website" target="_blank"><img src="https://opencollective.com/nest/backer/35/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/36/website" target="_blank"><img src="https://opencollective.com/nest/backer/36/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/37/website" target="_blank"><img src="https://opencollective.com/nest/backer/37/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/38/website" target="_blank"><img src="https://opencollective.com/nest/backer/38/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/39/website" target="_blank"><img src="https://opencollective.com/nest/backer/39/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/40/website" target="_blank"><img src="https://opencollective.com/nest/backer/40/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/41/website" target="_blank"><img src="https://opencollective.com/nest/backer/41/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/42/website" target="_blank"><img src="https://opencollective.com/nest/backer/42/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/43/website" target="_blank"><img src="https://opencollective.com/nest/backer/43/avatar.svg"></a>
## People
## Stay in touch
- Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](LICENSE).
<h4 align="center"> <a href="readme_zh.md">中文说明</a></h4>

View File

@@ -1,2 +1,4 @@
export * from './interfaces';
export * from './test';
export * from './testing-module.builder';
export * from './testing-module';

View File

@@ -10,3 +10,5 @@ function __export(m) {
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(require("./test"));
__export(require("./testing-module.builder"));
__export(require("./testing-module"));

View File

@@ -1,6 +1,6 @@
{
"name": "@nestjs/testing",
"version": "4.6.1",
"version": "4.6.6",
"description": "Nest - modern, fast, powerful node.js web framework (@testing)",
"author": "Kamil Mysliwiec",
"license": "MIT",

View File

@@ -10,8 +10,14 @@ class TestingModule extends core_1.NestApplicationContext {
constructor(container, scope, contextModule) {
super(container, scope, contextModule);
}
<<<<<<< HEAD
createNestApplication(httpServer = express_factory_1.ExpressFactory.create()) {
return new core_1.NestApplication(this.container, httpServer, new application_config_1.ApplicationConfig());
=======
createNestApplication(expressInstance = express()) {
this.container.setApplicationRef(expressInstance);
return new core_1.NestApplication(this.container, expressInstance, new application_config_1.ApplicationConfig());
>>>>>>> master
}
createNestMicroservice(config) {
if (!NestMicroservice) {

View File

@@ -7,14 +7,14 @@
[linux-image]: https://img.shields.io/travis/nestjs/nest/master.svg?label=linux
[linux-url]: https://travis-ci.org/nestjs/nest
<p align="center">A progressive <a href="http://nodejs.org" target="blank">Node.js</a> framework for building efficient and scalable web applications, heavily inspired by <a href="https://angular.io" target="blank">Angular</a>.</p>
<p align="center">A progressive <a href="http://nodejs.org" target="blank">Node.js</a> framework for building efficient and scalable server-side applications, heavily inspired by <a href="https://angular.io" target="blank">Angular</a>.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/dm/@nestjs/core.svg" alt="NPM Downloads" /></a>
<a href="https://travis-ci.org/nestjs/nest"><img src="https://api.travis-ci.org/nestjs/nest.svg?branch=master" alt="Travis" /></a>
<a href="https://travis-ci.org/nestjs/nest"><img src="https://img.shields.io/travis/nestjs/nest/master.svg?label=linux" alt="Linux" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#4" alt="Coverage" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#5" alt="Coverage" /></a>
<a href="https://gitter.im/nestjs/nestjs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=body_badge"><img src="https://badges.gitter.im/nestjs/nestjs.svg" alt="Gitter" /></a>
<a href="https://opencollective.com/nest#backer"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
@@ -24,7 +24,7 @@
## Description
<p>Nest is a framework for building efficient, scalable <a href="http://nodejs.org" target="_blank">Node.js</a> web applications. It uses modern JavaScript, is built with <a href="http://www.typescriptlang.org" target="_blank">TypeScript</a> (preserves compatibility with pure JavaScript) and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).</p>
<p>Nest is a framework for building efficient, scalable <a href="http://nodejs.org" target="_blank">Node.js</a> server-side applications. It uses modern JavaScript, is built with <a href="http://www.typescriptlang.org" target="_blank">TypeScript</a> (preserves compatibility with pure JavaScript) and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).</p>
<p>Under the hood, Nest makes use of <a href="https://expressjs.com/" target="_blank">Express</a>, allowing for easy use of the myriad third-party plugins which are available.</p>
## Philosophy
@@ -36,11 +36,16 @@
To check out the [guide](https://docs.nestjs.com), visit [docs.nestjs.com](https://docs.nestjs.com). :books:
## Sponsors
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://opencollective.com/nest). Thanks! :heart_eyes:
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://opencollective.com/nest).
<a href="https://valor-software.com/"><img src="https://docs.nestjs.com/assets/sponsors/valor-software.png" width="210" /></a>
#### Principal Sponsor
<a href="https://valor-software.com/"><img src="https://docs.nestjs.com/assets/sponsors/valor-software.png" width="210" /></a>
#### Sponsors
<a href="https://scal.io"><img src="https://nestjs.com/img/scalio-logo.svg" width="160" /></a> &nbsp; <a href="https://www.swingdev.io"><img src="https://nestjs.com/img/swingdev-logo.svg#1" width="160" /></a>
## Backers
@@ -74,12 +79,29 @@ Nest is an MIT-licensed open source project. It can grow thanks to the sponsors
<a href="https://opencollective.com/nest/backer/27/website" target="_blank"><img src="https://opencollective.com/nest/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/28/website" target="_blank"><img src="https://opencollective.com/nest/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/29/website" target="_blank"><img src="https://opencollective.com/nest/backer/29/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/30/website" target="_blank"><img src="https://opencollective.com/nest/backer/30/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/31/website" target="_blank"><img src="https://opencollective.com/nest/backer/31/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/32/website" target="_blank"><img src="https://opencollective.com/nest/backer/32/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/33/website" target="_blank"><img src="https://opencollective.com/nest/backer/33/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/34/website" target="_blank"><img src="https://opencollective.com/nest/backer/34/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/35/website" target="_blank"><img src="https://opencollective.com/nest/backer/35/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/36/website" target="_blank"><img src="https://opencollective.com/nest/backer/36/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/37/website" target="_blank"><img src="https://opencollective.com/nest/backer/37/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/38/website" target="_blank"><img src="https://opencollective.com/nest/backer/38/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/39/website" target="_blank"><img src="https://opencollective.com/nest/backer/39/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/40/website" target="_blank"><img src="https://opencollective.com/nest/backer/40/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/41/website" target="_blank"><img src="https://opencollective.com/nest/backer/41/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/42/website" target="_blank"><img src="https://opencollective.com/nest/backer/42/avatar.svg"></a>
<a href="https://opencollective.com/nest/backer/43/website" target="_blank"><img src="https://opencollective.com/nest/backer/43/avatar.svg"></a>
## People
## Stay in touch
- Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](LICENSE).
<h4 align="center"> <a href="readme_zh.md">中文说明</a></h4>

View File

@@ -1,6 +1,6 @@
{
"name": "@nestjs/websockets",
"version": "4.6.5",
"version": "4.6.6",
"description": "Nest - modern, fast, powerful node.js web framework (@websockets)",
"author": "Kamil Mysliwiec",
"license": "MIT",
@@ -9,9 +9,9 @@
"socket.io": "^2.0.3"
},
"peerDependencies": {
"@nestjs/common": "^4.*",
"@nestjs/core": "^4.*",
"reflect-metadata": "0.1.10",
"rxjs": "^5.4.2"
"@nestjs/common": "^5.*",
"@nestjs/core": "^5.*",
"reflect-metadata": "0.1.12",
"rxjs": "^5.5.6"
}
}

3582
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,10 +1,11 @@
{
"name": "nestjs",
"version": "4.6.5",
"version": "4.6.6",
"description": "Modern, fast, powerful node.js web framework",
"main": "index.js",
"scripts": {
"test": "nyc --require ts-node/register mocha src/**/*.spec.ts --reporter spec",
"integration-test": "mocha integration/**/*.spec.ts --reporter spec --require ts-node/register",
"coverage": "nyc report --reporter=text-lcov | coveralls",
"prettier": "prettier */**/*.ts --ignore-path ./.prettierignore --write && git status",
"build": "gulp build && gulp move",
@@ -16,6 +17,10 @@
"engines": {
"node": ">=6.11.0"
},
"repository": {
"type": "git",
"url": "https://github.com/nestjs/nest"
},
"author": "Kamil Mysliwiec",
"license": "MIT",
"dependencies": {
@@ -24,7 +29,6 @@
"@nestjs/microservices": "^4.0.0",
"@nestjs/testing": "^4.0.0",
"@nestjs/websockets": "^4.0.0",
"@types/axios": "^0.14.0",
"axios": "^0.17.1",
"class-transformer": "^0.1.8",
"class-validator": "^0.8.1",
@@ -47,7 +51,6 @@
"rxjs-grpc": "^0.1.6",
"socket.io": "^2.0.3",
"trouter": "^1.0.0",
"turbo-http": "^0.1.1",
"typescript": "^2.4.1"
},
"devDependencies": {
@@ -72,7 +75,9 @@
"coveralls": "^2.11.16",
"gulp": "^3.9.1",
"gulp-clang-format": "^1.0.23",
"gulp-clean": "^0.4.0",
"gulp-sequence": "^0.4.6",
"gulp-sourcemaps": "^2.6.4",
"gulp-typescript": "^3.1.6",
"gulp-watch": "^4.3.11",
"imports-loader": "^0.7.0",

View File

@@ -2,4 +2,4 @@ export * from './request-mapping.decorator';
export * from './route-params.decorator';
export * from './http-code.decorator';
export * from './create-route-param-metadata.decorator';
export * from './render.decorator';
export * from './render.decorator';

View File

@@ -8,5 +8,5 @@ export enum RouteParamtypes {
HEADERS,
SESSION,
FILE,
FILES
FILES,
}

View File

@@ -1,16 +1,12 @@
import axios from 'axios';
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { Observable } from 'rxjs/Observable';
import {
AxiosRequestConfig,
AxiosResponse,
} from './interfaces/axios.interfaces';
import { fromPromise } from 'rxjs/observable/fromPromise';
export class HttpService {
request<T = any>(config: AxiosRequestConfig): Observable<AxiosResponse<T>> {
return fromPromise(axios.request<T>(config));
}
get<T = any>(
url: string,
config?: AxiosRequestConfig,

View File

@@ -1,2 +1,2 @@
export * from './http.module';
export * from './http.service';
export * from './http.service';

View File

@@ -1,127 +0,0 @@
export interface AxiosTransformer {
(data: any, headers?: any): any;
}
export interface AxiosAdapter {
(config: AxiosRequestConfig): AxiosPromise<any>;
}
export interface AxiosBasicCredentials {
username: string;
password: string;
}
export interface AxiosProxyConfig {
host: string;
port: number;
}
export interface AxiosRequestConfig {
url?: string;
method?: string;
baseURL?: string;
transformRequest?: AxiosTransformer | AxiosTransformer[];
transformResponse?: AxiosTransformer | AxiosTransformer[];
headers?: any;
params?: any;
paramsSerializer?: (params: any) => string;
data?: any;
timeout?: number;
withCredentials?: boolean;
adapter?: AxiosAdapter;
auth?: AxiosBasicCredentials;
responseType?: string;
xsrfCookieName?: string;
xsrfHeaderName?: string;
onUploadProgress?: (progressEvent: any) => void;
onDownloadProgress?: (progressEvent: any) => void;
maxContentLength?: number;
validateStatus?: (status: number) => boolean;
maxRedirects?: number;
httpAgent?: any;
httpsAgent?: any;
proxy?: AxiosProxyConfig;
cancelToken?: CancelToken;
}
export interface AxiosResponse<T = any> {
data: T;
status: number;
statusText: string;
headers: any;
config: AxiosRequestConfig;
request?: any;
}
export interface AxiosError extends Error {
config: AxiosRequestConfig;
code?: string;
request?: any;
response?: AxiosResponse;
}
export interface AxiosPromise<T = any> extends Promise<AxiosResponse<T>> {
}
export interface CancelStatic {
new (message?: string): Cancel;
}
export interface Cancel {
message: string;
}
export interface Canceler {
(message?: string): void;
}
export interface CancelTokenStatic {
new (executor: (cancel: Canceler) => void): CancelToken;
source(): CancelTokenSource;
}
export interface CancelToken {
promise: Promise<Cancel>;
reason?: Cancel;
throwIfRequested(): void;
}
export interface CancelTokenSource {
token: CancelToken;
cancel: Canceler;
}
export interface AxiosInterceptorManager<V> {
use(onFulfilled?: (value: V) => V | Promise<V>, onRejected?: (error: any) => any): number;
eject(id: number): void;
}
export interface AxiosInstance {
defaults: AxiosRequestConfig;
interceptors: {
request: AxiosInterceptorManager<AxiosRequestConfig>;
response: AxiosInterceptorManager<AxiosResponse>;
};
request<T = any>(config: AxiosRequestConfig): AxiosPromise<T>;
get<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>;
delete(url: string, config?: AxiosRequestConfig): AxiosPromise;
head(url: string, config?: AxiosRequestConfig): AxiosPromise;
post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>;
put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>;
patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>;
}
export interface AxiosStatic extends AxiosInstance {
(config: AxiosRequestConfig): AxiosPromise;
(url: string, config?: AxiosRequestConfig): AxiosPromise;
create(config?: AxiosRequestConfig): AxiosInstance;
Cancel: CancelStatic;
CancelToken: CancelTokenStatic;
isCancel(value: any): boolean;
all<T>(values: (T | Promise<T>)[]): Promise<T[]>;
spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
}
declare const Axios: AxiosStatic;
export default Axios;

View File

@@ -4,7 +4,11 @@ import { Observable } from 'rxjs/Observable';
import { MulterOptions } from '../interfaces/external/multer-options.interface';
import { transformException } from './multer/multer.utils';
export function FilesInterceptor(fieldName: string, maxCount?: number, options?: MulterOptions) {
export function FilesInterceptor(
fieldName: string,
maxCount?: number,
options?: MulterOptions,
) {
const Interceptor = class implements NestInterceptor {
readonly upload = multer(options);

View File

@@ -1,2 +1,2 @@
export * from './file.interceptor';
export * from './files.interceptor';
export * from './files.interceptor';

View File

@@ -1,4 +1,9 @@
import { InternalServerErrorException, HttpException, PayloadTooLargeException, BadRequestException } from './../../exceptions';
import {
InternalServerErrorException,
HttpException,
PayloadTooLargeException,
BadRequestException,
} from './../../exceptions';
import { multerExceptions } from './multer.constants';
export function transformException(error: Error | undefined) {
@@ -6,15 +11,15 @@ export function transformException(error: Error | undefined) {
return error;
}
switch (error.message) {
case multerExceptions.LIMIT_FILE_SIZE:
case multerExceptions.LIMIT_FILE_SIZE:
return new PayloadTooLargeException(error.message);
case multerExceptions.LIMIT_FILE_COUNT:
case multerExceptions.LIMIT_FIELD_KEY:
case multerExceptions.LIMIT_FIELD_VALUE:
case multerExceptions.LIMIT_FIELD_KEY:
case multerExceptions.LIMIT_FIELD_VALUE:
case multerExceptions.LIMIT_FIELD_COUNT:
case multerExceptions.LIMIT_UNEXPECTED_FILE:
case multerExceptions.LIMIT_PART_COUNT:
return new BadRequestException(error.message);
}
return error;
}
}

View File

@@ -4,12 +4,12 @@ export interface ErrorHandler {
(
error: any,
req: Partial<IncomingMessage>,
res: ServerResponse,
next: Function,
res: ServerResponse | any,
next?: Function,
): any;
}
export interface RequestHandler {
(req: Partial<IncomingMessage>, res: ServerResponse, next: Function): any;
(req: Partial<IncomingMessage>, res: ServerResponse | any, next?: Function): any;
}
export interface HttpServer {

View File

@@ -69,7 +69,11 @@ export interface INestApplication extends INestApplicationContext {
* @returns Promise
*/
listen(port: number | string, callback?: () => void): Promise<any>;
listen(port: number | string, hostname: string, callback?: () => void): Promise<any>;
listen(
port: number | string,
hostname: string,
callback?: () => void,
): Promise<any>;
/**
* Starts the application and can be awaited.

View File

@@ -33,7 +33,9 @@ export class ValidationPipe implements PipeTransform<any> {
}
return this.isTransformEnabled
? entity
: Object.keys(this.validatorOptions).length > 0 ? classToPlain(entity) : value;
: Object.keys(this.validatorOptions).length > 0
? classToPlain(entity)
: value;
}
private toValidate(metadata: ArgumentMetadata): boolean {

View File

@@ -183,7 +183,6 @@ describe('@Patch', () => {
});
});
describe('Inheritance', () => {
const requestPath = 'test';
const requestProps = {

View File

@@ -16,9 +16,11 @@ describe('FileInterceptor', () => {
});
it('should call single() with expected params', async () => {
const fieldName = 'file';
const target = new (FileInterceptor(fieldName));
const target = new (FileInterceptor(fieldName))();
const callback = (req, res, next) => next();
const singleSpy = sinon.stub((target as any).upload, 'single').returns(callback);
const singleSpy = sinon
.stub((target as any).upload, 'single')
.returns(callback);
const req = {};
await target.intercept(req, null, stream$);

View File

@@ -17,10 +17,12 @@ describe('FilesInterceptor', () => {
it('should call array() with expected params', async () => {
const fieldName = 'file';
const maxCount = 10;
const target = new (FilesInterceptor(fieldName, maxCount));
const target = new (FilesInterceptor(fieldName, maxCount))();
const callback = (req, res, next) => next();
const arraySpy = sinon.stub((target as any).upload, 'array').returns(callback);
const arraySpy = sinon
.stub((target as any).upload, 'array')
.returns(callback);
await target.intercept({}, null, stream$);

View File

@@ -19,8 +19,7 @@ describe('ParseIntPipe', () => {
});
describe('when validation fails', () => {
it('should throw an error', async () => {
return expect(target.transform('123abc', {} as any)).to.be
.rejected;
return expect(target.transform('123abc', {} as any)).to.be.rejected;
});
});
});

View File

@@ -27,9 +27,9 @@ describe('ValidationPipe', () => {
it('should return the value unchanged', async () => {
const testObj = { prop1: 'value1', prop2: 'value2' };
expect(await target.transform(testObj, {} as any)).to.equal(testObj);
expect(await target.transform(testObj, metadata as any)).to.not.be.instanceOf(
TestModel,
);
expect(
await target.transform(testObj, metadata as any),
).to.not.be.instanceOf(TestModel);
});
});
describe('when validation fails', () => {
@@ -43,43 +43,55 @@ describe('ValidationPipe', () => {
});
describe('when validation transforms', () => {
it('should return a TestModel instance', async () => {
target = new ValidationPipe({transform: true});
const testObj = { prop1: 'value1', prop2: 'value2', prop3: 'value3'};
expect(await target.transform(testObj, metadata)).to.be.instanceOf(TestModel);
target = new ValidationPipe({ transform: true });
const testObj = { prop1: 'value1', prop2: 'value2', prop3: 'value3' };
expect(await target.transform(testObj, metadata)).to.be.instanceOf(
TestModel,
);
});
describe('when validation strips', () => {
it('should return a TestModel without extra properties', async () => {
target = new ValidationPipe({whitelist: true});
const testObj = { prop1: 'value1', prop2: 'value2', prop3: 'value3'};
expect(await target.transform(testObj, metadata)).to.not.be.instanceOf(TestModel);
expect(await target.transform(testObj, metadata)).to.not.have.property('prop3');
target = new ValidationPipe({ whitelist: true });
const testObj = { prop1: 'value1', prop2: 'value2', prop3: 'value3' };
expect(
await target.transform(testObj, metadata),
).to.not.be.instanceOf(TestModel);
expect(
await target.transform(testObj, metadata),
).to.not.have.property('prop3');
});
});
describe('when validation rejects', () => {
it('should throw an error', () => {
target = new ValidationPipe({forbidNonWhitelisted: true});
target = new ValidationPipe({ forbidNonWhitelisted: true });
const testObj = { prop1: 'value1', prop2: 'value2', prop3: 'value3' };
expect(target.transform(testObj, metadata)).to.be.rejected;
});
});
});
describe('when validation does\'t transform', () => {
describe("when validation does't transform", () => {
describe('when validation strips', () => {
it('should return a plain object without extra properties', async () => {
target = new ValidationPipe({transform: false, whitelist: true});
const testObj = { prop1: 'value1', prop2: 'value2', prop3: 'value3'};
expect(await target.transform(testObj, metadata)).to.not.be.instanceOf(TestModel);
expect(await target.transform(testObj, metadata)).to.not.have.property('prop3');
target = new ValidationPipe({ transform: false, whitelist: true });
const testObj = { prop1: 'value1', prop2: 'value2', prop3: 'value3' };
expect(
await target.transform(testObj, metadata),
).to.not.be.instanceOf(TestModel);
expect(
await target.transform(testObj, metadata),
).to.not.have.property('prop3');
});
});
describe('when validation rejects', () => {
it('should throw an error', () => {
target = new ValidationPipe({transform: false, forbidNonWhitelisted: true});
target = new ValidationPipe({
transform: false,
forbidNonWhitelisted: true,
});
const testObj = { prop1: 'value1', prop2: 'value2', prop3: 'value3' };
expect(target.transform(testObj, metadata)).to.be.rejected;
});
});
});
});
});
});

View File

@@ -2,7 +2,4 @@ export const createHttpExceptionBody = (
message: any,
error: string,
statusCode: number,
) =>
message
? { statusCode, error, message }
: { statusCode, error };
) => (message ? { statusCode, error, message } : { statusCode, error });

View File

@@ -6,8 +6,6 @@ import {
import { isNil, isObject } from '@nestjs/common/utils/shared.utils';
export class ExpressAdapter implements HttpServer {
private readonly isExpress = true;
constructor(private readonly instance) {}
use(handler: RequestHandler | ErrorHandler);

View File

@@ -36,7 +36,7 @@ export class ApplicationConfig implements ConfigurationProvider {
public addGlobalPipe(pipe: PipeTransform<any>) {
this.globalPipes.push(pipe);
}
public useGlobalPipes(...pipes: PipeTransform<any>[]) {
this.globalPipes = this.globalPipes.concat(pipes);
}

View File

@@ -8,4 +8,4 @@ export const messages = {
export const APP_INTERCEPTOR = 'APP_INTERCEPTOR';
export const APP_PIPE = 'APP_PIPE';
export const APP_GUARD = 'APP_GUARD';
export const APP_FILTER = 'APP_FILTER';
export const APP_FILTER = 'APP_FILTER';

View File

@@ -18,10 +18,10 @@ export const InvalidMiddlewareMessage = (name: string) =>
`The middleware doesn't provide the 'resolve' method (${name})`;
export const InvalidModuleMessage = (scope: string) =>
`Nest can't create the module instance. The frequent reason of this exception is the circular dependency between modules. Use forwardRef() to avoid it (read more https://docs.nestjs.com/advanced/circular-dependency). Scope [${scope}]`;
`Nest cannot create the module instance. The frequent reason of this exception is the circular dependency between modules. Use forwardRef() to avoid it (read more https://docs.nestjs.com/advanced/circular-dependency). Scope [${scope}]`;
export const UnknownExportMessage = (name: string) =>
`You are trying to export unknown component (${name}). Remember - your component should be listed both in exports and components arrays!`;
export const UnknownExportMessage = (module: string) =>
`Nest cannot export component / module that is not a part of the currently proccessed module (${module}). Please verify whether each exported unit is available in this particular context.`;
export const INVALID_MIDDLEWARE_CONFIGURATION = `Invalid middleware configuration passed inside the module 'configure()' method.`;
export const UNKNOWN_REQUEST_MAPPING = `Request mapping properties not defined in the @RequestMapping() annotation!`;

View File

@@ -1,2 +1,2 @@
export * from './modules-container';
export * from './tokens';
export * from './tokens';

View File

@@ -353,10 +353,12 @@ export class Injector {
modules.map((module: Module) => {
const { relatedModules, exports } = module;
return this.flatMap(
[...relatedModules.values()].filter(related => {
const { metatype } = related;
return exports.has(metatype.name);
}),
[...relatedModules.values()]
.filter(related => !!related)
.filter(related => {
const { metatype } = related;
return exports.has(metatype.name);
}),
);
}),
);

View File

@@ -135,7 +135,7 @@ export class Module {
name: HTTP_SERVER_REF,
metatype: {} as any,
isResolved: true,
instance: applicationRef,
instance: applicationRef || {},
});
}
@@ -269,15 +269,18 @@ export class Module {
public addExportedComponent(
exportedComponent: ComponentMetatype | string | DynamicModule,
) {
const addExportedUnit = (token: string) =>
this._exports.add(this.validateExportedProvider(token));
if (this.isCustomProvider(exportedComponent as any)) {
return this.addCustomExportedComponent(exportedComponent as any);
} else if (isString(exportedComponent)) {
return this._exports.add(exportedComponent);
return addExportedUnit(exportedComponent);
} else if (this.isDynamicModule(exportedComponent)) {
const { module } = exportedComponent;
return this._exports.add(module.name);
return addExportedUnit(module.name);
}
this._exports.add(exportedComponent.name);
addExportedUnit(exportedComponent.name);
}
public addCustomExportedComponent(
@@ -285,9 +288,26 @@ export class Module {
) {
const provide = exportedComponent.provide;
if (isString(provide) || isSymbol(provide)) {
return this._exports.add(provide);
return this._exports.add(this.validateExportedProvider(provide));
}
this._exports.add(provide.name);
this._exports.add(this.validateExportedProvider(provide.name));
}
public validateExportedProvider(token: string) {
if (this._components.has(token)) {
return token;
}
const relatedModules = [...this._relatedModules.values()];
const modulesTokens = relatedModules
.map(({ metatype }) => metatype)
.filter(metatype => !!metatype)
.map(({ name }) => name);
if (modulesTokens.indexOf(token) < 0) {
const { name } = this.metatype;
throw new UnknownExportException(name);
}
return token;
}
public addRoute(route: Type<Controller>) {

View File

@@ -1 +1 @@
export const HTTP_SERVER_REF = 'HTTP_SERVER_REF';
export const HTTP_SERVER_REF = 'HTTP_SERVER_REF';

View File

@@ -28,7 +28,7 @@ export class MetadataScanner {
}
return !isConstructor(prop) && isFunction(prototype[prop]);
})
.toArray()
.toArray();
} while (
(prototype = Reflect.getPrototypeOf(prototype)) &&
prototype != Object.prototype

View File

@@ -39,6 +39,8 @@ import { NestApplicationContext } from './nest-application-context';
import { HttpsOptions } from '@nestjs/common/interfaces/external/https-options.interface';
import { NestApplicationOptions } from '@nestjs/common/interfaces/nest-application-options.interface';
import { CorsOptions } from '@nestjs/common/interfaces/external/cors-options.interface';
import { HttpServer } from '@nestjs/common/interfaces';
import { ExpressAdapter } from './adapters/express-adapter';
const { SocketModule } =
optional('@nestjs/websockets/socket-module') || ({} as any);
@@ -65,7 +67,7 @@ export class NestApplication extends NestApplicationContext
constructor(
container: NestContainer,
private readonly httpAdapter: any,
private httpAdapter: HttpServer,
private readonly config: ApplicationConfig,
private readonly appOptions: NestApplicationOptions = {},
) {
@@ -74,6 +76,7 @@ export class NestApplication extends NestApplicationContext
this.applyOptions();
this.selectContextModule();
this.registerHttpServer();
this.routesResolver = new RoutesResolver(this.container, this.config);
}
@@ -98,17 +101,22 @@ export class NestApplication extends NestApplicationContext
public createServer(): any {
const isHttpsEnabled = this.appOptions && this.appOptions.httpsOptions;
if (isHttpsEnabled && this.httpAdapter.isExpress) {
return https.createServer(this.appOptions.httpsOptions, this.httpAdapter);
const isExpress = this.isExpress();
if (isHttpsEnabled && isExpress) {
return https.createServer(
this.appOptions.httpsOptions,
this.httpAdapter.getHttpServer(),
);
}
if (this.httpAdapter.isExpress) {
if (isExpress) {
return http.createServer(this.httpAdapter.getHttpServer());
}
return this.httpAdapter;
}
public getUnderlyingHttpServer(): any {
return this.httpAdapter.isExpress
return this.isExpress()
? this.httpServer
: this.httpAdapter.getHttpServer();
}
@@ -143,7 +151,7 @@ export class NestApplication extends NestApplicationContext
}
public registerParserMiddlewares() {
if (!this.httpAdapter.isExpress) {
if (!this.isExpress()) {
return void 0;
}
const parserMiddlewares = {
@@ -155,7 +163,8 @@ export class NestApplication extends NestApplicationContext
.forEach(parserKey => this.httpAdapter.use(parserMiddlewares[parserKey]));
}
public isMiddlewareApplied(app, name: string): boolean {
public isMiddlewareApplied(httpAdapter: HttpServer, name: string): boolean {
const app = this.httpAdapter.getHttpServer();
return (
!!app._router &&
!!app._router.stack &&
@@ -185,7 +194,7 @@ export class NestApplication extends NestApplicationContext
config as any,
applicationConfig,
);
instance.setupListeners();
instance.registerListeners();
instance.setIsInitialized(true);
instance.setIsInitHookCalled(true);
@@ -212,28 +221,40 @@ export class NestApplication extends NestApplicationContext
return new Promise(resolve => this.startAllMicroservices(resolve));
}
public use(...args): this {
this.httpAdapter.use(...args);
public use(...args: any[]): this {
(this.httpAdapter as any).use(...args);
return this;
}
public engine(...args): this {
this.httpAdapter.engine && this.httpAdapter.engine(...args);
if (!this.isExpress()) {
return this;
}
(this.httpAdapter as ExpressAdapter).engine(...args);
return this;
}
public set(...args): this {
this.httpAdapter.set && this.httpAdapter.set(...args);
if (!this.isExpress()) {
return this;
}
(this.httpAdapter as ExpressAdapter).set(...args);
return this;
}
public disable(...args): this {
this.httpAdapter.disable && this.httpAdapter.disable(...args);
if (!this.isExpress()) {
return this;
}
(this.httpAdapter as ExpressAdapter).disable(...args);
return this;
}
public enable(...args): this {
this.httpAdapter.enable && this.httpAdapter.enable(...args);
if (!this.isExpress()) {
return this;
}
(this.httpAdapter as ExpressAdapter).enable(...args);
return this;
}
@@ -308,6 +329,14 @@ export class NestApplication extends NestApplicationContext
);
}
private isExpress(): boolean {
const isExpress = !this.httpAdapter.getHttpServer;
if (isExpress) {
return isExpress;
}
return this.httpAdapter instanceof ExpressAdapter;
}
private listenToPromise(microservice: INestMicroservice) {
return new Promise(async (resolve, reject) => {
await microservice.listen(resolve);

View File

@@ -23,6 +23,7 @@ import { HttpsOptions } from '@nestjs/common/interfaces/external/https-options.i
import { NestApplicationContextOptions } from '@nestjs/common/interfaces/nest-application-context-options.interface';
import { NestMicroserviceOptions } from '@nestjs/common/interfaces/microservices/nest-microservice-options.interface';
import { ApplicationConfig } from './application-config';
import { ExpressAdapter } from './adapters/express-adapter';
const { NestMicroservice } =
optional('@nestjs/microservices/nest-microservice') || ({} as any);
@@ -40,7 +41,7 @@ export class NestFactoryStatic {
): Promise<INestApplication>;
public async create(
module: any,
httpServer: HttpServer,
httpServer: HttpServer | any,
options?: NestApplicationOptions,
): Promise<INestApplication>;
public async create(
@@ -49,27 +50,18 @@ export class NestFactoryStatic {
options?: NestApplicationOptions,
): Promise<INestApplication> {
const isHttpServer = serverOrOptions && serverOrOptions.patch;
const [httpServer, appOptions] = isHttpServer
let [httpServer, appOptions] = isHttpServer
? [serverOrOptions, options]
: [ExpressFactory.create(), serverOrOptions];
const applicationConfig = new ApplicationConfig();
const container = new NestContainer(applicationConfig);
httpServer = this.applyExpressAdapter(httpServer);
this.applyLogger(appOptions);
await this.initialize(
module,
container,
applicationConfig,
httpServer,
);
await this.initialize(module, container, applicationConfig, httpServer);
return this.createNestInstance<NestApplication>(
new NestApplication(
container,
httpServer,
applicationConfig,
appOptions,
),
new NestApplication(container, httpServer, applicationConfig, appOptions),
);
}
@@ -180,6 +172,14 @@ export class NestFactoryStatic {
}
Logger.overrideLogger(options.logger);
}
private applyExpressAdapter(httpAdapter: HttpServer): HttpServer {
const isAdapter = !!httpAdapter.getHttpServer;
if (isAdapter) {
return httpAdapter;
}
return new ExpressAdapter(httpAdapter);
}
}
export const NestFactory = new NestFactoryStatic();

View File

@@ -27,7 +27,7 @@ export class RouteParamsFactory implements IRouteParamsFactory {
case RouteParamtypes.FILE:
return req.file;
case RouteParamtypes.FILES:
return req.files;
return req.files;
default:
return null;
}

View File

@@ -213,6 +213,9 @@ describe('Module', () => {
});
describe('when exported component is custom provided', () => {
beforeEach(() => {
sinon.stub(module, 'validateExportedProvider').callsFake(o => o);
});
it('should call `addCustomExportedComponent`', () => {
const addCustomExportedComponentSpy = sinon.spy(
module,
@@ -308,4 +311,30 @@ describe('Module', () => {
});
});
});
describe('validateExportedProvider', () => {
const token = 'token';
describe('when unit exists in component collection', () => {
it('should behave as identity', () => {
(module as any)._components = new Map([[token, true]]);
expect(module.validateExportedProvider(token)).to.be.eql(token);
});
});
describe('when unit exists in related modules collection', () => {
it('should behave as identity', () => {
const metatype = { name: token };
(module as any)._relatedModules = new Set([
new Module(metatype as any, [], new NestContainer()),
]);
expect(module.validateExportedProvider(token)).to.be.eql(token);
});
});
describe('when unit does not exist in both component and related modules collections', () => {
it('should throw UnknownExportException', () => {
expect(() => module.validateExportedProvider(token)).to.throws(
UnknownExportException,
);
});
});
});
});

View File

@@ -75,14 +75,18 @@ describe('InterceptorsConsumer', () => {
it('should return Observable', async () => {
const val = 3;
const next = async () => val;
expect(await (await consumer.transformDeffered(next).toPromise())).to.be.eql(val);
expect(
await await consumer.transformDeffered(next).toPromise(),
).to.be.eql(val);
});
});
describe('when next() result is Promise', () => {
it('should return Observable', async () => {
const val = 3;
const next = () => Promise.resolve(val);
expect(await (await consumer.transformDeffered(next).toPromise())).to.be.eql(val);
expect(
await await consumer.transformDeffered(next).toPromise(),
).to.be.eql(val);
});
});
describe('when next() result is Observable', () => {

View File

@@ -16,7 +16,7 @@ describe('MetadataScanner', () => {
}
set valParent(value) {}
}
class Test extends Parent {
constructor() {
super();

View File

@@ -106,10 +106,7 @@ describe('RouteParamsFactory', () => {
describe(`RouteParamtypes.FILE`, () => {
it('should returns file object', () => {
expect(
(factory as any).exchangeKeyForValue(
RouteParamtypes.FILE,
...args,
),
(factory as any).exchangeKeyForValue(RouteParamtypes.FILE, ...args),
).to.be.eql(req.file);
});
});

View File

@@ -336,7 +336,7 @@ describe('RouterExecutionContext', () => {
const template = 'template';
const value = 'test';
const response = { render: sinon.spy() };
sinon.stub(contextCreator, 'reflectRenderTemplate').returns(template);
const handler = contextCreator.createHandleResponseFn(null, true, 100);
handler(value, response);
@@ -348,7 +348,7 @@ describe('RouterExecutionContext', () => {
it('should not call "res.render()"', () => {
const result = Promise.resolve('test');
const response = { render: sinon.spy() };
sinon.stub(contextCreator, 'reflectRenderTemplate').returns(undefined);
const handler = contextCreator.createHandleResponseFn(null, true, 100);
handler(result, response);

View File

@@ -84,7 +84,10 @@ describe('RoutesResolver', () => {
const spy = sinon
.stub(routesResolver, 'registerRouters')
.callsFake(() => undefined);
routesResolver.resolve({ use: sinon.spy() } as any, { use: sinon.spy() } as any);
routesResolver.resolve(
{ use: sinon.spy() } as any,
{ use: sinon.spy() } as any,
);
expect(spy.calledTwice).to.be.true;
});
});

View File

@@ -198,7 +198,7 @@ describe('DependenciesScanner', () => {
mockContainer.expects('addComponent').callsFake(() => false);
scanner.storeComponent(component, token);
const applyMap = (scanner as any).applicationProvidersApplyMap;
expect(applyMap).to.have.length(1);
expect(applyMap[0].moduleToken).to.be.eql(token);
});
@@ -219,28 +219,33 @@ describe('DependenciesScanner', () => {
expectation.verify();
});
it('should not push new object to "applicationProvidersApplyMap" array', () => {
expect(
(scanner as any).applicationProvidersApplyMap
).to.have.length(0);
expect((scanner as any).applicationProvidersApplyMap).to.have.length(
0,
);
mockContainer.expects('addComponent').callsFake(() => false);
scanner.storeComponent(component, token);
expect(
(scanner as any).applicationProvidersApplyMap
).to.have.length(0);
expect((scanner as any).applicationProvidersApplyMap).to.have.length(
0,
);
});
});
});
});
describe('applyApplicationProviders', () => {
it('should apply each provider', () => {
const provider = { moduleToken: 'moduleToken', providerToken: 'providerToken' };
const provider = {
moduleToken: 'moduleToken',
providerToken: 'providerToken',
};
(scanner as any).applicationProvidersApplyMap = [provider];
const expectedInstance = {};
mockContainer.expects('getModules').callsFake(() => ({ get: () => ({
components: { get: () => ({ instance: expectedInstance }) }
})}));
mockContainer.expects('getModules').callsFake(() => ({
get: () => ({
components: { get: () => ({ instance: expectedInstance }) },
}),
}));
const applySpy = sinon.spy();
sinon.stub(scanner, 'getApplyProvidersMap').callsFake(() => ({
[provider.providerToken]: applySpy,
@@ -254,7 +259,8 @@ describe('DependenciesScanner', () => {
describe(`when token is ${APP_INTERCEPTOR}`, () => {
it('call "addGlobalInterceptor"', () => {
const addSpy = sinon.spy(
(scanner as any).applicationConfig, 'addGlobalInterceptor'
(scanner as any).applicationConfig,
'addGlobalInterceptor',
);
scanner.getApplyProvidersMap()[APP_INTERCEPTOR](null);
expect(addSpy.called).to.be.true;
@@ -263,7 +269,8 @@ describe('DependenciesScanner', () => {
describe(`when token is ${APP_GUARD}`, () => {
it('call "addGlobalGuard"', () => {
const addSpy = sinon.spy(
(scanner as any).applicationConfig, 'addGlobalGuard'
(scanner as any).applicationConfig,
'addGlobalGuard',
);
scanner.getApplyProvidersMap()[APP_GUARD](null);
expect(addSpy.called).to.be.true;
@@ -272,7 +279,8 @@ describe('DependenciesScanner', () => {
describe(`when token is ${APP_PIPE}`, () => {
it('call "addGlobalPipe"', () => {
const addSpy = sinon.spy(
(scanner as any).applicationConfig, 'addGlobalPipe'
(scanner as any).applicationConfig,
'addGlobalPipe',
);
scanner.getApplyProvidersMap()[APP_PIPE](null);
expect(addSpy.called).to.be.true;
@@ -281,7 +289,8 @@ describe('DependenciesScanner', () => {
describe(`when token is ${APP_FILTER}`, () => {
it('call "addGlobalFilter"', () => {
const addSpy = sinon.spy(
(scanner as any).applicationConfig, 'addGlobalFilter'
(scanner as any).applicationConfig,
'addGlobalFilter',
);
scanner.getApplyProvidersMap()[APP_FILTER](null);
expect(addSpy.called).to.be.true;

View File

@@ -28,8 +28,9 @@ export class ClientRedis extends ClientProxy {
const pattern = JSON.stringify(msg.pattern);
const responseCallback = (channel, message) => {
const { err, response, disposed } = JSON.parse(message);
if (disposed) {
callback(null, null, true);
if (disposed || err) {
callback(err, null, true);
this.subClient.unsubscribe(this.getResPatternName(pattern));
this.subClient.removeListener(MESSAGE_EVENT, responseCallback);
return;

View File

@@ -60,8 +60,8 @@ export class ClientTCP extends ClientProxy {
context: Function,
) {
const { err, response, disposed } = buffer;
if (disposed) {
callback(null, null, true);
if (disposed || err) {
callback(err, null, true);
return socket._socket.removeListener(MESSAGE_EVENT, context);
}
callback(err, response);

View File

@@ -116,7 +116,7 @@ export class NestMicroservice extends NestApplicationContext
}
public async listenAsync(): Promise<any> {
return await new Promise((resolve) => this.listen(resolve));
return await new Promise(resolve => this.listen(resolve));
}
public close() {

View File

@@ -72,8 +72,7 @@ export class ServerRedis extends Server implements CustomTransportStrategy {
const status = 'error';
if (!this.messageHandlers[pattern]) {
publish({ status, error: NO_PATTERN_MESSAGE });
return;
return publish({ status, err: NO_PATTERN_MESSAGE });
}
const handler = this.messageHandlers[pattern];
const response$ = this.transformToObservable(

View File

@@ -40,9 +40,9 @@ export class ServerTCP extends Server implements CustomTransportStrategy {
public async handleMessage(socket, msg: { pattern: any; data: {} }) {
const pattern = JSON.stringify(msg.pattern);
const status = 'error';
if (!this.messageHandlers[pattern]) {
socket.sendMessage({ status, error: NO_PATTERN_MESSAGE });
return;
return socket.sendMessage({ status, err: NO_PATTERN_MESSAGE });
}
const handler = this.messageHandlers[pattern];
const response$ = this.transformToObservable(

View File

@@ -78,19 +78,25 @@ describe('ClientRedis', () => {
});
describe('responseCallback', () => {
let callback, subscription;
const resMsg = {
err: 'err',
const responseMessage = {
err: null,
response: 'test',
};
describe('not disposed', () => {
beforeEach(() => {
callback = sinon.spy();
<<<<<<< HEAD
subscription = client['sendMessage'](msg, callback);
subscription(null, JSON.stringify(resMsg));
=======
subscription = client['sendSingleMessage'](msg, callback);
subscription(null, JSON.stringify(responseMessage));
>>>>>>> master
});
it('should call callback with expected arguments', () => {
expect(callback.calledWith(resMsg.err, resMsg.response)).to.be.true;
expect(callback.calledWith(null, responseMessage.response)).to.be
.true;
});
it('should not unsubscribe to response pattern name', () => {
expect(unsubscribeSpy.calledWith(`"${pattern}"_res`)).to.be.false;
@@ -107,7 +113,7 @@ describe('ClientRedis', () => {
});
it('should call callback with dispose param', () => {
expect(callback.called).to.be.true;
expect(callback.calledWith(null, null, true)).to.be.true;
expect(callback.calledWith(undefined, null, true)).to.be.true;
});
it('should unsubscribe to response pattern name', () => {
expect(unsubscribeSpy.calledWith(`"${pattern}"_res`)).to.be.true;

View File

@@ -86,14 +86,14 @@ describe('ClientTCP', () => {
});
it('should emit disposed callback', () => {
expect(callback.called).to.be.true;
expect(callback.calledWith(null, null, true)).to.be.true;
expect(callback.calledWith(undefined, null, true)).to.be.true;
});
});
describe('when not disposed', () => {
let buffer;
const context = () => ({});
beforeEach(() => {
buffer = { err: 'test', response: 'res' };
buffer = { err: null, response: 'res' };
callback = sinon.spy();
client.handleResponse(socket, callback, buffer, context);
});

View File

@@ -96,7 +96,7 @@ describe('ServerRedis', () => {
expect(
getPublisherSpy.calledWith({
status: 'error',
error: NO_PATTERN_MESSAGE,
err: NO_PATTERN_MESSAGE,
}),
).to.be.true;
});

View File

@@ -60,7 +60,7 @@ describe('ServerTCP', () => {
expect(
socket.sendMessage.calledWith({
status: 'error',
error: NO_PATTERN_MESSAGE,
err: NO_PATTERN_MESSAGE,
}),
).to.be.true;
});

Some files were not shown because too many files have changed in this diff Show More