Skip to content

Commit

Permalink
feature(http-adapter) Added the application's global prefix to the er…
Browse files Browse the repository at this point in the history
…ror and not found handlers, cors and body parser registrations, and enabled the adapters to register them based on prefix.
  • Loading branch information
boenrobot committed Dec 17, 2019
1 parent 9acaa9b commit 2fbbee4
Show file tree
Hide file tree
Showing 8 changed files with 68 additions and 40 deletions.
8 changes: 4 additions & 4 deletions packages/common/interfaces/http/http-server.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ export interface HttpServer<TRequest = any, TResponse = any> {
render(response: any, view: string, options: any): any;
redirect(response: any, statusCode: number, url: string): any;
setHeader(response: any, name: string, value: string): any;
setErrorHandler?(handler: Function): any;
setNotFoundHandler?(handler: Function): any;
setErrorHandler?(handler: Function, prefix?: string): any;
setNotFoundHandler?(handler: Function, prefix?: string): any;
useStaticAssets?(...args: any[]): this;
setBaseViewsDir?(path: string | string[]): this;
setViewEngine?(engineOrOptions: any): this;
Expand All @@ -58,8 +58,8 @@ export interface HttpServer<TRequest = any, TResponse = any> {
getRequestMethod?(request: TRequest): string;
getRequestUrl?(request: TResponse): string;
getInstance(): any;
registerParserMiddleware(): any;
enableCors(options: CorsOptions): any;
registerParserMiddleware(prefix?: string): any;
enableCors(options: CorsOptions, prefix?: string): any;
getHttpServer(): any;
initHttpServer(options: NestApplicationOptions): void;
close(): any;
Expand Down
4 changes: 2 additions & 2 deletions packages/common/interfaces/nest-application.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ export interface INestApplication extends INestApplicationContext {
/**
* Enables CORS (Cross-Origin Resource Sharing)
*
* @returns {void}
* @returns {Promise<void>}
*/
enableCors(options?: CorsOptions): this;
enableCors(options?: CorsOptions): Promise<void>;

/**
* Starts the application.
Expand Down
8 changes: 4 additions & 4 deletions packages/core/adapters/http-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,11 @@ export abstract class AbstractHttpAdapter<
abstract reply(response, body: any, statusCode?: number);
abstract render(response, view: string, options: any);
abstract redirect(response, statusCode: number, url: string);
abstract setErrorHandler(handler: Function);
abstract setNotFoundHandler(handler: Function);
abstract setErrorHandler(handler: Function, prefix?: string);
abstract setNotFoundHandler(handler: Function, prefix?: string);
abstract setHeader(response, name: string, value: string);
abstract registerParserMiddleware();
abstract enableCors(options: CorsOptions);
abstract registerParserMiddleware(prefix?: string);
abstract enableCors(options: CorsOptions, prefix?: string);
abstract createMiddlewareFactory(
requestMethod: RequestMethod,
): (path: string, callback: Function) => any;
Expand Down
15 changes: 7 additions & 8 deletions packages/core/nest-application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ export class NestApplication extends NestApplicationContext
) {
super(container);

this.applyOptions();
this.selectContextModule();
this.registerHttpServer();

Expand Down Expand Up @@ -105,7 +104,7 @@ export class NestApplication extends NestApplicationContext
if (!isCorsOptionsObj) {
return this.enableCors();
}
this.enableCors(this.appOptions.cors as CorsOptions);
return this.enableCors(this.appOptions.cors as CorsOptions);
}

public createServer<T = any>(): T {
Expand Down Expand Up @@ -138,8 +137,9 @@ export class NestApplication extends NestApplicationContext
public async init(): Promise<this> {
const useBodyParser =
this.appOptions && this.appOptions.bodyParser !== false;
useBodyParser && this.registerParserMiddleware();
useBodyParser && await this.registerParserMiddleware(this.config.getGlobalPrefix());

await this.applyOptions();
await this.registerModules();
await this.registerRouter();
await this.callInitHook();
Expand All @@ -151,8 +151,8 @@ export class NestApplication extends NestApplicationContext
return this;
}

public registerParserMiddleware() {
this.httpAdapter.registerParserMiddleware();
public async registerParserMiddleware(prefix: string = '/') {
return this.httpAdapter.registerParserMiddleware(prefix);
}

public async registerRouter() {
Expand Down Expand Up @@ -213,9 +213,8 @@ export class NestApplication extends NestApplicationContext
return this;
}

public enableCors(options?: CorsOptions): this {
this.httpAdapter.enableCors(options);
return this;
public async enableCors(options?: CorsOptions): Promise<void> {
return this.httpAdapter.enableCors(options, this.config.getGlobalPrefix());
}

public async listen(
Expand Down
4 changes: 2 additions & 2 deletions packages/core/router/routes-resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ export class RoutesResolver implements Resolver {
const handler = this.routerExceptionsFilter.create({}, callback, undefined);
const proxy = this.routerProxy.createProxy(callback, handler);
applicationRef.setNotFoundHandler &&
applicationRef.setNotFoundHandler(proxy);
applicationRef.setNotFoundHandler(proxy, this.config.getGlobalPrefix());
}

public registerExceptionHandler() {
Expand All @@ -105,7 +105,7 @@ export class RoutesResolver implements Resolver {
);
const proxy = this.routerProxy.createExceptionLayerProxy(callback, handler);
const applicationRef = this.container.getHttpAdapterRef();
applicationRef.setErrorHandler && applicationRef.setErrorHandler(proxy);
applicationRef.setErrorHandler && applicationRef.setErrorHandler(proxy, this.config.getGlobalPrefix());
}

public mapExternalException(err: any) {
Expand Down
8 changes: 4 additions & 4 deletions packages/core/test/utils/noop-adapter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@ export class NoopHttpAdapter extends AbstractHttpAdapter {
status(response: any, statusCode: number): any {}
render(response: any, view: string, options: any): any {}
redirect(response: any, statusCode: number, url: string) {}
setErrorHandler(handler: Function): any {}
setNotFoundHandler(handler: Function): any {}
setErrorHandler(handler: Function, prefix: string = '/'): any {}
setNotFoundHandler(handler: Function, prefix: string = '/'): any {}
setHeader(response: any, name: string, value: string): any {}
registerParserMiddleware(): any {}
enableCors(options: any): any {}
registerParserMiddleware(prefix: string = '/'): any {}
enableCors(options: any, prefix: string = '/'): any {}
createMiddlewareFactory(requestMethod: RequestMethod): any {}
getType() {
return '';
Expand Down
16 changes: 8 additions & 8 deletions packages/platform-express/adapters/express-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,12 @@ export class ExpressAdapter extends AbstractHttpAdapter {
return response.redirect(statusCode, url);
}

public setErrorHandler(handler: Function) {
return this.use(handler);
public setErrorHandler(handler: Function, prefix: string = '/') {
return this.use(prefix, handler);
}

public setNotFoundHandler(handler: Function) {
return this.use(handler);
public setNotFoundHandler(handler: Function, prefix: string = '/') {
return this.use(prefix, handler);
}

public setHeader(response: any, name: string, value: string) {
Expand Down Expand Up @@ -101,8 +101,8 @@ export class ExpressAdapter extends AbstractHttpAdapter {
return request.url;
}

public enableCors(options: CorsOptions) {
this.use(cors(options));
public enableCors(options: CorsOptions, prefix: string = '/') {
this.use(prefix, cors(options));
}

public createMiddlewareFactory(
Expand All @@ -125,14 +125,14 @@ export class ExpressAdapter extends AbstractHttpAdapter {
this.httpServer = http.createServer(this.getInstance());
}

public registerParserMiddleware() {
public registerParserMiddleware(prefix: string = '/') {
const parserMiddleware = {
jsonParser: bodyParser.json(),
urlencodedParser: bodyParser.urlencoded({ extended: true }),
};
Object.keys(parserMiddleware)
.filter(parser => !this.isMiddlewareApplied(parser))
.forEach(parserKey => this.use(parserMiddleware[parserKey]));
.forEach(parserKey => this.use(prefix, parserMiddleware[parserKey]));
}

public getType(): string {
Expand Down
45 changes: 37 additions & 8 deletions packages/platform-fastify/adapters/fastify-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,22 @@ export class FastifyAdapter extends AbstractHttpAdapter {
return response.status(code).redirect(url);
}

public setErrorHandler(handler: Function) {
return this.instance.setErrorHandler(handler);
public async setErrorHandler(
handler: Parameters<fastify.FastifyInstance['setErrorHandler']>[0],
prefix: string = '/',
): Promise<void> {
return this.registerWithPrefix(async (instance: fastify.FastifyInstance) => {
instance.setErrorHandler(handler);
}, prefix);
}

public setNotFoundHandler(handler: Function) {
return this.instance.setNotFoundHandler(handler);
public async setNotFoundHandler(
handler: Parameters<fastify.FastifyInstance['setNotFoundHandler']>[0],
prefix: string = '/',
): Promise<void> {
return this.registerWithPrefix(async (instance: fastify.FastifyInstance) => {
instance.setNotFoundHandler(handler);
}, prefix);
}

public getHttpServer<T = any>(): T {
Expand Down Expand Up @@ -132,12 +142,16 @@ export class FastifyAdapter extends AbstractHttpAdapter {
return request.raw.url;
}

public enableCors(options: CorsOptions) {
this.register(cors, options);
public async enableCors(options: CorsOptions, prefix: string = '/') {
return this.registerWithPrefix(async (instance: fastify.FastifyInstance) => {
instance.register(cors, options);
}, prefix);
}

public registerParserMiddleware() {
this.register(formBody);
public registerParserMiddleware(prefix: string = '/') {
return this.registerWithPrefix(async (instance: fastify.FastifyInstance) => {
instance.register(formBody);
}, prefix);
}

public createMiddlewareFactory(
Expand Down Expand Up @@ -171,4 +185,19 @@ export class FastifyAdapter extends AbstractHttpAdapter {
public getType(): string {
return 'fastify';
}

protected registerWithPrefix(
factory: (instance: fastify.FastifyInstance) => Promise<void>,
prefix: string = '/',
): Promise<void> {
return new Promise((done, error) =>
this.instance.register(factory, { prefix }).after(err => {
if (err) {
error(err);
} else {
done();
}
}),
);
}
}

0 comments on commit 2fbbee4

Please sign in to comment.