feature(@nestjs/core) better type checking for fastify adapter

This commit is contained in:
Kamil Myśliwiec
2018-03-14 14:27:12 +01:00
parent fc092ae0b3
commit e481a71b5c
43 changed files with 3839 additions and 730 deletions

2
.gitignore vendored
View File

@@ -27,4 +27,4 @@ yarn-error.log
/integration
/coverage
/.nyc_output
build/config\.gypi
build/config\.gypi

View File

@@ -5,7 +5,7 @@ import { FastifyAdapter } from '@nestjs/core/adapters/fastify-adapter';
import * as fastify from 'fastify';
async function bootstrap() {
const app = await NestFactory.create(ApplicationModule, new FastifyAdapter(fastify()));
const app = await NestFactory.create(ApplicationModule);
app.useGlobalPipes(new ValidationPipe());
await app.listen(3000);
}

File diff suppressed because it is too large Load Diff

View File

@@ -3,13 +3,13 @@ export declare class HttpException extends Error {
private readonly status;
readonly message: any;
/**
<<<<<<< HEAD
<<<<<<< HEAD
* The base Nest Application exception which is handled by the default Exceptions Handler.
* If you throw an exception from your HTTP route handlers, Nest will map them to the appropriate HTTP response and send to the client.
=======
=======
* The base Nest Application exception, which is handled by the default Exceptions Handler.
* If you throw an exception from your HTTP route handler, Nest will map them to the appropriate HTTP response and send to the client.
>>>>>>> master
>>>>>>> master
*
* When `response` is an object:
* - object will be stringified and returned to the user as a JSON response,

View File

@@ -2,13 +2,13 @@
Object.defineProperty(exports, "__esModule", { value: true });
class HttpException extends Error {
/**
<<<<<<< HEAD
<<<<<<< HEAD
* The base Nest Application exception which is handled by the default Exceptions Handler.
* If you throw an exception from your HTTP route handlers, Nest will map them to the appropriate HTTP response and send to the client.
=======
=======
* The base Nest Application exception, which is handled by the default Exceptions Handler.
* If you throw an exception from your HTTP route handler, Nest will map them to the appropriate HTTP response and send to the client.
>>>>>>> master
>>>>>>> master
*
* When `response` is an object:
* - object will be stringified and returned to the user as a JSON response,

View File

@@ -1,10 +1,5 @@
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>>;

View File

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

View File

@@ -1,10 +1,10 @@
/// <reference types="node" />
import { IncomingMessage, ServerResponse } from 'http';
export interface ErrorHandler {
(error: any, req: Partial<IncomingMessage>, res: ServerResponse, next: Function): any;
(error: any, req: Partial<IncomingMessage>, 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 {
use(handler: RequestHandler | ErrorHandler): any;

View File

@@ -1,4 +1,5 @@
import { Type } from './../type.interface';
export interface MiddlewareConfiguration {
middlewares: any;
forRoutes: string[];
forRoutes: (Type<any> | string)[];
}

View File

@@ -9,14 +9,10 @@ export interface INestApplicationContext {
* Retrieves an instance of either injectable or controller available inside the processed module, otherwise, returns null.
* @returns T
*/
<<<<<<< HEAD
get<T>(typeOrToken: Type<T> | string | symbol): T | null;
/**
* Retrieves an instance of either injectable or controller available inside any module, otherwise, returns null.
* @returns T
*/
find<T>(typeOrToken: Type<T> | string | symbol): T | null;
=======
get<T>(metatypeOrToken: Metatype<T> | string | symbol): T;
>>>>>>> master
}

View File

@@ -12,7 +12,7 @@ export interface INestApplication extends INestApplicationContext {
*/
init(): Promise<this>;
/**
* A wrapper function around native `express.use()` method.
* A wrapper function around HTTP adapter method: `adapter.use()`.
* Example `app.use(cors())`
*
* @returns void

View File

@@ -0,0 +1,30 @@
export interface INestExpressApplication {
/**
* A wrapper function around native `express.set()` method.
* Example `app.set('trust proxy', 'loopback')`
*
* @returns void
*/
set(...args: any[]): this;
/**
* A wrapper function around native `express.engine()` method.
* Example `app.engine('mustache', mustacheExpress())`
*
* @returns void
*/
engine(...args: any[]): this;
/**
* A wrapper function around native `express.enable()` method.
* Example `app.enable('x-powered-by')`
*
* @returns void
*/
enable(...args: any[]): this;
/**
* A wrapper function around native `express.disable()` method.
* Example `app.disable('x-powered-by')`
*
* @returns void
*/
disable(...args: any[]): this;
}

View File

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

View File

@@ -0,0 +1,9 @@
export interface INestFastifyApplication {
/**
* A wrapper function around native `fastify.register()` method.
* Example `app.register(require('fastify-formbody'))`
*
* @returns void
*/
register(...args: any[]): this;
}

View File

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

View File

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

View File

@@ -1,7 +1,6 @@
import { HttpServer, RequestHandler, ErrorHandler } from '@nestjs/common/interfaces';
export declare class ExpressAdapter implements HttpServer {
private readonly instance;
private readonly isExpress;
constructor(instance: any);
use(handler: RequestHandler | ErrorHandler): any;
use(path: any, handler: RequestHandler | ErrorHandler): any;

View File

@@ -4,7 +4,6 @@ const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
class ExpressAdapter {
constructor(instance) {
this.instance = instance;
this.isExpress = true;
}
use(pathOrHandler, handler) {
return handler

View File

@@ -54,12 +54,8 @@ 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
addRoute(route: Type<Controller>): void;
addRelatedModule(relatedModule: any): void;
replace(toReplace: any, options: any): string;
createModuleRefMetatype(components: any): {

View File

@@ -32,11 +32,7 @@ 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

@@ -6,18 +6,10 @@ export declare class NestApplicationContext implements INestApplicationContext {
private readonly scope;
protected contextModule: any;
private readonly moduleTokenFactory;
<<<<<<< HEAD
constructor(container: NestContainer, scope: Type<any>[], contextModule: any);
selectContextModule(): void;
select<T>(module: Type<T>): INestApplicationContext;
get<T>(typeOrToken: Type<T> | string | symbol): T | null;
find<T>(typeOrToken: Type<T> | string | symbol): T | null;
private findInstanceByPrototypeOrToken<T>(metatypeOrToken, contextModule);
=======
constructor(container: NestContainer, scope: NestModuleMetatype[], contextModule: any);
selectContextModule(): void;
select<T>(module: Metatype<T>): INestApplicationContext;
get<T>(metatypeOrToken: Metatype<T> | string | symbol): T;
private findInstanceByPrototypeOrToken<T>(metatypeOrToken);
>>>>>>> master
}

View File

@@ -8,8 +8,9 @@ import { NestContainer } from './injector/container';
import { NestApplicationContext } from './nest-application-context';
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';
export declare class NestApplication extends NestApplicationContext implements INestApplication {
private readonly httpAdapter;
private httpAdapter;
private readonly config;
private readonly appOptions;
private readonly logger;
@@ -21,20 +22,15 @@ export declare class NestApplication extends NestApplicationContext implements I
private readonly microservices;
private httpServer;
private isInitialized;
<<<<<<< HEAD
constructor(container: NestContainer, httpAdapter: any, config: ApplicationConfig, appOptions?: NestApplicationOptions);
constructor(container: NestContainer, httpAdapter: HttpServer, config: ApplicationConfig, appOptions?: NestApplicationOptions);
registerHttpServer(): void;
applyOptions(): any;
=======
constructor(container: NestContainer, express: any, config: ApplicationConfig, appOptions?: NestApplicationOptions);
applyOptions(): this;
>>>>>>> master
createServer(): any;
getUnderlyingHttpServer(): any;
registerModules(): Promise<void>;
init(): Promise<this>;
registerParserMiddlewares(): any;
isMiddlewareApplied(app: any, name: string): boolean;
isMiddlewareApplied(httpAdapter: HttpServer, name: string): boolean;
registerRouter(): Promise<void>;
connectMicroservice(config: MicroserviceConfiguration): INestMicroservice;
getMicroservices(): INestMicroservice[];
@@ -58,6 +54,7 @@ export declare class NestApplication extends NestApplicationContext implements I
useGlobalInterceptors(...interceptors: NestInterceptor[]): this;
useGlobalGuards(...guards: CanActivate[]): this;
private registerMiddlewares(instance);
private isExpress();
private listenToPromise(microservice);
private callInitHook();
private callModuleInitHook(module);

View File

@@ -23,6 +23,7 @@ const routes_resolver_1 = require("./router/routes-resolver");
const microservices_package_not_found_exception_1 = require("./errors/exceptions/microservices-package-not-found.exception");
const container_1 = require("./middlewares/container");
const nest_application_context_1 = require("./nest-application-context");
const express_adapter_1 = require("./adapters/express-adapter");
const { SocketModule } = optional('@nestjs/websockets/socket-module') || {};
const { MicroservicesModule } = optional('@nestjs/microservices/microservices-module') || {};
const { NestMicroservice } = optional('@nestjs/microservices/nest-microservice') || {};
@@ -65,16 +66,17 @@ class NestApplication extends nest_application_context_1.NestApplicationContext
}
createServer() {
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;
}
getUnderlyingHttpServer() {
return this.httpAdapter.isExpress
return this.isExpress()
? this.httpServer
: this.httpAdapter.getHttpServer();
}
@@ -102,7 +104,7 @@ class NestApplication extends nest_application_context_1.NestApplicationContext
});
}
registerParserMiddlewares() {
if (!this.httpAdapter.isExpress) {
if (!this.isExpress()) {
return void 0;
}
const parserMiddlewares = {
@@ -113,7 +115,8 @@ class NestApplication extends nest_application_context_1.NestApplicationContext
.filter(parser => !this.isMiddlewareApplied(this.httpAdapter, parser))
.forEach(parserKey => this.httpAdapter.use(parserMiddlewares[parserKey]));
}
isMiddlewareApplied(app, name) {
isMiddlewareApplied(httpAdapter, name) {
const app = this.httpAdapter.getHttpServer();
return (!!app._router &&
!!app._router.stack &&
shared_utils_1.isFunction(app._router.stack.filter) &&
@@ -133,7 +136,7 @@ class NestApplication extends nest_application_context_1.NestApplicationContext
}
const applicationConfig = new application_config_1.ApplicationConfig();
const instance = new NestMicroservice(this.container, config, applicationConfig);
instance.setupListeners();
instance.registerListeners();
instance.setIsInitialized(true);
instance.setIsInitHookCalled(true);
this.microservices.push(instance);
@@ -157,23 +160,35 @@ class NestApplication extends nest_application_context_1.NestApplicationContext
return this;
}
engine(...args) {
this.httpAdapter.engine && this.httpAdapter.engine(...args);
if (!this.isExpress()) {
return this;
}
this.httpAdapter.engine(...args);
return this;
}
set(...args) {
this.httpAdapter.set && this.httpAdapter.set(...args);
if (!this.isExpress()) {
return this;
}
this.httpAdapter.set(...args);
return this;
}
disable(...args) {
this.httpAdapter.disable && this.httpAdapter.disable(...args);
if (!this.isExpress()) {
return this;
}
this.httpAdapter.disable(...args);
return this;
}
enable(...args) {
this.httpAdapter.enable && this.httpAdapter.enable(...args);
if (!this.isExpress()) {
return this;
}
this.httpAdapter.enable(...args);
return this;
}
enableCors() {
this.httpAdapter.use(cors());
enableCors(options) {
this.httpAdapter.use(cors(options));
return this;
}
listen(port, ...args) {
@@ -226,6 +241,13 @@ class NestApplication extends nest_application_context_1.NestApplicationContext
yield this.middlewaresModule.registerMiddlewares(this.middlewaresContainer, instance);
});
}
isExpress() {
const isExpress = !this.httpAdapter.getHttpServer;
if (isExpress) {
return isExpress;
}
return this.httpAdapter instanceof express_adapter_1.ExpressAdapter;
}
listenToPromise(microservice) {
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
yield microservice.listen(resolve);

View File

@@ -1,16 +1,20 @@
import { NestApplicationOptions } from '@nestjs/common/interfaces/nest-application-options.interface';
import { INestMicroservice, INestApplicationContext, HttpServer } from '@nestjs/common';
import { INestApplication, INestMicroservice, INestApplicationContext, HttpServer } from '@nestjs/common';
import { NestApplicationContextOptions } from '@nestjs/common/interfaces/nest-application-context-options.interface';
import { NestMicroserviceOptions } from '@nestjs/common/interfaces/microservices/nest-microservice-options.interface';
import { INestExpressApplication } from '@nestjs/common/interfaces/nest-express-application.interface';
import { FastifyAdapter } from './adapters/fastify-adapter';
import { INestFastifyApplication } from '@nestjs/common/interfaces/nest-fastify-application.interface';
export declare class NestFactoryStatic {
private readonly logger;
/**
* Creates an instance of the NestApplication (returns Promise)
* @returns an `Promise` of the INestApplication instance
*/
create(module: any): any;
create(module: any, options: NestApplicationOptions): any;
create(module: any, httpServer: HttpServer, options?: NestApplicationOptions): any;
create(module: any): Promise<INestApplication & INestExpressApplication>;
create(module: any, options: NestApplicationOptions): Promise<INestApplication & INestExpressApplication>;
create(module: any, httpServer: HttpServer | any, options?: NestApplicationOptions): Promise<INestApplication & INestExpressApplication>;
create(module: any, httpServer: FastifyAdapter, options?: NestApplicationOptions): Promise<INestApplication & INestFastifyApplication>;
/**
* Creates an instance of the NestMicroservice (returns Promise)
*
@@ -32,5 +36,6 @@ export declare class NestFactoryStatic {
private createProxy(target);
private createExceptionProxy();
private applyLogger(options);
private applyExpressAdapter(httpAdapter);
}
export declare const NestFactory: NestFactoryStatic;

View File

@@ -22,6 +22,7 @@ const metadata_scanner_1 = require("./metadata-scanner");
const microservices_package_not_found_exception_1 = require("./errors/exceptions/microservices-package-not-found.exception");
const nest_application_context_1 = require("./nest-application-context");
const application_config_1 = require("./application-config");
const express_adapter_1 = require("./adapters/express-adapter");
const { NestMicroservice } = optional('@nestjs/microservices/nest-microservice') || {};
class NestFactoryStatic {
constructor() {
@@ -29,20 +30,13 @@ class NestFactoryStatic {
}
create(module, serverOrOptions, options) {
return __awaiter(this, void 0, void 0, function* () {
<<<<<<< HEAD
const isHttpServer = serverOrOptions && serverOrOptions.patch;
const [httpServer, appOptions] = isHttpServer
let [httpServer, appOptions] = isHttpServer
? [serverOrOptions, options]
: [express_factory_1.ExpressFactory.create(), serverOrOptions];
const container = new container_1.NestContainer();
=======
const isExpressInstance = expressOrOptions && expressOrOptions.response;
const [expressInstance, appOptions] = isExpressInstance
? [expressOrOptions, options]
: [express_adapter_1.ExpressAdapter.create(), expressOrOptions];
>>>>>>> master
const applicationConfig = new application_config_1.ApplicationConfig();
const container = new container_1.NestContainer(applicationConfig);
httpServer = this.applyExpressAdapter(httpServer);
this.applyLogger(appOptions);
yield this.initialize(module, container, applicationConfig, httpServer);
return this.createNestInstance(new nest_application_1.NestApplication(container, httpServer, applicationConfig, appOptions));
@@ -134,6 +128,13 @@ class NestFactoryStatic {
}
logger_service_1.Logger.overrideLogger(options.logger);
}
applyExpressAdapter(httpAdapter) {
const isAdapter = !!httpAdapter.getHttpServer;
if (isAdapter) {
return httpAdapter;
}
return new express_adapter_1.ExpressAdapter(httpAdapter);
}
}
exports.NestFactoryStatic = NestFactoryStatic;
exports.NestFactory = new NestFactoryStatic();

View File

@@ -10,18 +10,10 @@ export declare class RoutesResolver implements Resolver {
private readonly routerProxy;
private readonly routerExceptionsFilter;
private readonly routerBuilder;
<<<<<<< HEAD
constructor(container: NestContainer, config: ApplicationConfig);
resolve(appInstance: any, basePath: string): void;
registerRouters(routes: Map<string, InstanceWrapper<Controller>>, moduleName: string, basePath: string, appInstance: HttpServer): void;
registerNotFoundHandler(): void;
registerExceptionHandler(): void;
=======
constructor(container: NestContainer, expressAdapter: any, config: ApplicationConfig);
resolve(router: any, express: Application): void;
setupRouters(routes: Map<string, InstanceWrapper<Controller>>, moduleName: string, modulePath: string, express: Application): void;
setupNotFoundHandler(express: Application): void;
setupExceptionHandler(express: Application): void;
>>>>>>> master
mapExternalException(err: any): any;
}

View File

@@ -26,14 +26,8 @@ class RoutesResolver {
path = path ? path + basePath : basePath;
this.registerRouters(routes, moduleName, path, appInstance);
});
<<<<<<< HEAD
this.registerNotFoundHandler();
this.registerExceptionHandler();
=======
this.setupNotFoundHandler(router);
this.setupExceptionHandler(router);
this.setupExceptionHandler(express);
>>>>>>> master
}
registerRouters(routes, moduleName, basePath, appInstance) {
routes.forEach(({ instance, metatype }) => {
@@ -71,13 +65,5 @@ class RoutesResolver {
return err;
}
}
mapExternalException(err) {
switch (true) {
case err instanceof SyntaxError:
return new common_1.BadRequestException(err.message);
default:
return err;
}
}
}
exports.RoutesResolver = RoutesResolver;

View File

@@ -19,17 +19,10 @@ 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
this.subClient.unsubscribe(this.getResPatternName(pattern));
this.subClient.removeListener(constants_1.MESSAGE_EVENT, responseCallback);
return;
}
callback(err, response);

View File

@@ -8,17 +8,10 @@ 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,15 +51,9 @@ 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
return socket._socket.removeListener(constants_1.MESSAGE_EVENT, context);
}
callback(err, response);
}

View File

@@ -44,16 +44,9 @@ class NestMicroservice extends nest_application_context_1.NestApplicationContext
this.server = strategy
? strategy
: 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);

View File

@@ -14,8 +14,8 @@ export declare class ServerRedis extends Server implements CustomTransportStrate
bindEvents(subClient: redis.RedisClient, pubClient: redis.RedisClient): void;
close(): void;
createRedisClient(): redis.RedisClient;
getMessageHandler(pub: any): (channel: any, buffer: any) => Promise<void>;
handleMessage(channel: any, buffer: any, pub: any): Promise<void>;
getMessageHandler(pub: any): (channel: any, buffer: any) => Promise<any>;
handleMessage(channel: any, buffer: any, pub: any): Promise<any>;
getPublisher(pub: any, pattern: any): (respond: any) => any;
tryParse(content: any): any;
getAckQueueName(pattern: any): string;

View File

@@ -15,12 +15,8 @@ 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
handleClose(): undefined | number | NodeJS.Timer;
private init();
private getSocketInstance(socket);
}

View File

@@ -8,4 +8,5 @@ export declare class TestingModule extends NestApplicationContext {
constructor(container: NestContainer, scope: Type<any>[], contextModule: any);
createNestApplication(httpServer?: HttpServer): INestApplication;
createNestMicroservice(config: MicroserviceConfiguration): INestMicroservice;
private applyExpressAdapter(httpAdapter);
}

View File

@@ -5,19 +5,16 @@ const core_1 = require("@nestjs/core");
const microservices_package_not_found_exception_1 = require("@nestjs/core/errors/exceptions/microservices-package-not-found.exception");
const application_config_1 = require("@nestjs/core/application-config");
const express_factory_1 = require("@nestjs/core/adapters/express-factory");
const express_adapter_1 = require("@nestjs/core/adapters/express-adapter");
const { NestMicroservice } = optional('@nestjs/microservices/nest-microservice') || {};
class TestingModule extends core_1.NestApplicationContext {
constructor(container, scope, contextModule) {
super(container, scope, contextModule);
}
<<<<<<< HEAD
createNestApplication(httpServer = express_factory_1.ExpressFactory.create()) {
httpServer = this.applyExpressAdapter(httpServer);
this.container.setApplicationRef(httpServer);
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) {
@@ -25,5 +22,12 @@ class TestingModule extends core_1.NestApplicationContext {
}
return new NestMicroservice(this.container, config, new application_config_1.ApplicationConfig());
}
applyExpressAdapter(httpAdapter) {
const isAdapter = !!httpAdapter.getHttpServer;
if (isAdapter) {
return httpAdapter;
}
return new express_adapter_1.ExpressAdapter(httpAdapter);
}
}
exports.TestingModule = TestingModule;

View File

@@ -51,7 +51,7 @@
"rxjs-grpc": "^0.1.6",
"socket.io": "^2.0.3",
"trouter": "^1.0.0",
"typescript": "^2.4.1"
"typescript": "^2.7.2"
},
"devDependencies": {
"@types/chai": "^3.5.2",

View File

@@ -14,37 +14,13 @@ export interface INestApplication extends INestApplicationContext {
init(): Promise<this>;
/**
* A wrapper function around native `express.use()` method.
* A wrapper function around HTTP adapter method: `adapter.use()`.
* Example `app.use(cors())`
*
* @returns void
*/
use(...args): this;
/**
* A wrapper function around native `express.set()` method.
* Example `app.set('trust proxy', 'loopback')`
*
* @returns void
*/
set(...args): this;
/**
* A wrapper function around native `express.engine()` method.
* Example `app.engine('mustache', mustacheExpress())`
*
* @returns void
*/
engine(...args): this;
/**
* A wrapper function around native `express.enable()` method.
* Example `app.enable('x-powered-by')`
*
* @returns void
*/
enable(...args): this;
/**
* Enables CORS (Cross-Origin Resource Sharing)
*
@@ -52,14 +28,6 @@ export interface INestApplication extends INestApplicationContext {
*/
enableCors(options?: CorsOptions): this;
/**
* A wrapper function around native `express.disable()` method.
* Example `app.disable('x-powered-by')`
*
* @returns void
*/
disable(...args): this;
/**
* Starts the application.
*

View File

@@ -0,0 +1,33 @@
export interface INestExpressApplication {
/**
* A wrapper function around native `express.set()` method.
* Example `app.set('trust proxy', 'loopback')`
*
* @returns void
*/
set(...args): this;
/**
* A wrapper function around native `express.engine()` method.
* Example `app.engine('mustache', mustacheExpress())`
*
* @returns void
*/
engine(...args): this;
/**
* A wrapper function around native `express.enable()` method.
* Example `app.enable('x-powered-by')`
*
* @returns void
*/
enable(...args): this;
/**
* A wrapper function around native `express.disable()` method.
* Example `app.disable('x-powered-by')`
*
* @returns void
*/
disable(...args): this;
}

View File

@@ -0,0 +1,9 @@
export interface INestFastifyApplication {
/**
* A wrapper function around native `fastify.register()` method.
* Example `app.register(require('fastify-formbody'))`
*
* @returns void
*/
register(...args): this;
}

View File

@@ -4,7 +4,7 @@ import {
ErrorHandler,
} from '@nestjs/common/interfaces';
export class FastifyAdapter implements HttpServer {
export class FastifyAdapter {
constructor(protected readonly instance) {}
use(handler: RequestHandler | ErrorHandler);
@@ -83,6 +83,10 @@ export class FastifyAdapter implements HttpServer {
return this.instance.server;
}
register(...args) {
return this.instance.register(...args);
}
close() {
return this.instance.close();
}

View File

@@ -41,6 +41,9 @@ import { NestApplicationOptions } from '@nestjs/common/interfaces/nest-applicati
import { CorsOptions } from '@nestjs/common/interfaces/external/cors-options.interface';
import { HttpServer } from '@nestjs/common/interfaces';
import { ExpressAdapter } from './adapters/express-adapter';
import { FastifyAdapter } from './adapters/fastify-adapter';
import { INestExpressApplication } from '@nestjs/common/interfaces/nest-express-application.interface';
import { INestFastifyApplication } from '@nestjs/common/interfaces/nest-fastify-application.interface';
const { SocketModule } =
optional('@nestjs/websockets/socket-module') || ({} as any);
@@ -52,7 +55,10 @@ const { IoAdapter } =
optional('@nestjs/websockets/adapters/io-adapter') || ({} as any);
export class NestApplication extends NestApplicationContext
implements INestApplication {
implements
INestApplication,
INestExpressApplication,
INestFastifyApplication {
private readonly logger = new Logger(NestApplication.name, true);
private readonly middlewaresModule = new MiddlewaresModule();
private readonly middlewaresContainer = new MiddlewaresContainer();
@@ -258,6 +264,12 @@ export class NestApplication extends NestApplicationContext
return this;
}
public register(...args): this {
const adapter = this.httpAdapter as FastifyAdapter;
adapter.register && adapter.register(...args);
return this;
}
public enableCors(options?: CorsOptions): this {
this.httpAdapter.use(cors(options));
return this;

View File

@@ -24,6 +24,9 @@ import { NestApplicationContextOptions } from '@nestjs/common/interfaces/nest-ap
import { NestMicroserviceOptions } from '@nestjs/common/interfaces/microservices/nest-microservice-options.interface';
import { ApplicationConfig } from './application-config';
import { ExpressAdapter } from './adapters/express-adapter';
import { INestExpressApplication } from '@nestjs/common/interfaces/nest-express-application.interface';
import { FastifyAdapter } from './adapters/fastify-adapter';
import { INestFastifyApplication } from '@nestjs/common/interfaces/nest-fastify-application.interface';
const { NestMicroservice } =
optional('@nestjs/microservices/nest-microservice') || ({} as any);
@@ -34,21 +37,30 @@ export class NestFactoryStatic {
* Creates an instance of the NestApplication (returns Promise)
* @returns an `Promise` of the INestApplication instance
*/
public async create(module: any): Promise<INestApplication>;
public async create(
module: any,
): Promise<INestApplication & INestExpressApplication>;
public async create(
module: any,
options: NestApplicationOptions,
): Promise<INestApplication>;
): Promise<INestApplication & INestExpressApplication>;
public async create(
module: any,
httpServer: HttpServer | any,
httpServer: FastifyAdapter,
options?: NestApplicationOptions,
): Promise<INestApplication>;
): Promise<INestApplication & INestFastifyApplication>;
public async create(
module: any,
httpServer: HttpServer,
options?: NestApplicationOptions,
): Promise<INestApplication & INestExpressApplication>;
public async create(
module: any,
serverOrOptions?: any,
options?: NestApplicationOptions,
): Promise<INestApplication> {
): Promise<
INestApplication & (INestExpressApplication | INestFastifyApplication)
> {
const isHttpServer = serverOrOptions && serverOrOptions.patch;
let [httpServer, appOptions] = isHttpServer
? [serverOrOptions, options]
@@ -57,7 +69,7 @@ export class NestFactoryStatic {
const applicationConfig = new ApplicationConfig();
const container = new NestContainer(applicationConfig);
httpServer = this.applyExpressAdapter(httpServer);
this.applyLogger(appOptions);
await this.initialize(module, container, applicationConfig, httpServer);
return this.createNestInstance<NestApplication>(

784
yarn.lock

File diff suppressed because it is too large Load Diff