Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(platform): added prefix to adapters #4186

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 44 additions & 7 deletions integration/hello-world/e2e/express-multiple.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,25 @@ describe('Hello world (express instance with multiple applications)', () => {
const module2 = await Test.createTestingModule({
imports: [ApplicationModule],
}).compile();
const module3 = await Test.createTestingModule({
imports: [ApplicationModule],
}).compile();

const adapter = new ExpressAdapter(express());

apps = [
module1.createNestApplication(adapter),
module1.createNestApplication(adapter).setGlobalPrefix('app1'),
module2.createNestApplication(adapter).setGlobalPrefix('/app2'),
module3.createNestApplication(adapter),
];
await Promise.all(apps.map(app => app.init()));

server = adapter.getInstance();
});

it(`/GET`, () => {
it(`/GET (app1)`, () => {
return request(server)
.get('/hello')
.get('/app1/hello')
.expect(200)
.expect('Hello world!');
});
Expand All @@ -42,9 +46,9 @@ describe('Hello world (express instance with multiple applications)', () => {
.expect('Hello world!');
});

it(`/GET (Promise/async)`, () => {
it(`/GET (app1 Promise/async)`, () => {
return request(server)
.get('/hello/async')
.get('/app1/hello/async')
.expect(200)
.expect('Hello world!');
});
Expand All @@ -56,9 +60,9 @@ describe('Hello world (express instance with multiple applications)', () => {
.expect('Hello world!');
});

it(`/GET (Observable stream)`, () => {
it(`/GET (app1 Observable stream)`, () => {
return request(server)
.get('/hello/stream')
.get('/app1/hello/stream')
.expect(200)
.expect('Hello world!');
});
Expand All @@ -70,6 +74,39 @@ describe('Hello world (express instance with multiple applications)', () => {
.expect('Hello world!');
});

it(`/GET (app1 NotFound)`, () => {
return request(server)
.get('/app1/cats')
.expect(404)
.expect({
statusCode: 404,
error: 'Not Found',
message: 'Cannot GET /cats',
});
});

it(`/GET (app2 NotFound)`, () => {
return request(server)
.get('/app2/cats')
.expect(404)
.expect({
statusCode: 404,
error: 'Not Found',
message: 'Cannot GET /cats',
});
});

it(`/GET (app3 NotFound)`, () => {
return request(server)
.get('/app3/cats')
.expect(404)
.expect({
statusCode: 404,
error: 'Not Found',
message: 'Cannot GET /app3/cats',
});
});

afterEach(async () => {
await Promise.all(apps.map(app => app.close()));
});
Expand Down
74 changes: 64 additions & 10 deletions integration/hello-world/e2e/fastify-multiple.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
/* Temporarily disabled due to various regressions

import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import { Test } from '@nestjs/testing';
import { expect } from 'chai';
import { fail } from 'assert';
import { ApplicationModule } from '../src/app.module';

describe('Hello world (fastify adapter with multiple applications)', () => {
Expand All @@ -16,25 +15,29 @@ describe('Hello world (fastify adapter with multiple applications)', () => {
const module2 = await Test.createTestingModule({
imports: [ApplicationModule],
}).compile();
const module3 = await Test.createTestingModule({
imports: [ApplicationModule],
}).compile();

adapter = new FastifyAdapter();

apps = [
module1.createNestApplication<NestFastifyApplication>(adapter),
module1.createNestApplication<NestFastifyApplication>(adapter).setGlobalPrefix('app1'),
module2
.createNestApplication<NestFastifyApplication>(adapter, {
bodyParser: false,
})
.setGlobalPrefix('/app2'),
module3.createNestApplication<NestFastifyApplication>(adapter),
];
await Promise.all(apps.map(app => app.init()));
});

it(`/GET`, () => {
it(`/GET (app1)`, () => {
return adapter
.inject({
method: 'GET',
url: '/hello',
url: '/app1/hello',
})
.then(({ payload }) => expect(payload).to.be.eql('Hello world!'));
});
Expand All @@ -48,11 +51,11 @@ describe('Hello world (fastify adapter with multiple applications)', () => {
.then(({ payload }) => expect(payload).to.be.eql('Hello world!'));
});

it(`/GET (Promise/async)`, () => {
it(`/GET (app1 Promise/async)`, () => {
return adapter
.inject({
method: 'GET',
url: '/hello/async',
url: '/app1/hello/async',
})
.then(({ payload }) => expect(payload).to.be.eql('Hello world!'));
});
Expand All @@ -66,11 +69,11 @@ describe('Hello world (fastify adapter with multiple applications)', () => {
.then(({ payload }) => expect(payload).to.be.eql('Hello world!'));
});

it(`/GET (Observable stream)`, () => {
it(`/GET (app1 Observable stream)`, () => {
return adapter
.inject({
method: 'GET',
url: '/hello/stream',
url: '/app1/hello/stream',
})
.then(({ payload }) => expect(payload).to.be.eql('Hello world!'));
});
Expand All @@ -84,8 +87,59 @@ describe('Hello world (fastify adapter with multiple applications)', () => {
.then(({ payload }) => expect(payload).to.be.eql('Hello world!'));
});

it(`/GET (app1 NotFound)`, () => {
return adapter
.inject({
method: 'GET',
url: '/app1/cats',
})
.then(
({ payload }) => {
expect(payload).to.be.eql(JSON.stringify({
statusCode: 404,
error: 'Not Found',
message: 'Cannot GET /app1/cats',
}));
},
);
});

it(`/GET (app2 NotFound)`, () => {
return adapter
.inject({
method: 'GET',
url: '/app2/cats',
})
.then(
({ payload }) => {
expect(payload).to.be.eql(JSON.stringify({
statusCode: 404,
error: 'Not Found',
message: 'Cannot GET /app2/cats',
}));
},
);
});

it(`/GET (app3 NotFound)`, () => {
return adapter
.inject({
method: 'GET',
url: '/app3/cats',
})
.then(
({ payload }) => {
expect(payload).to.be.eql(JSON.stringify({
statusCode: 404,
error: 'Not Found',
message: 'Cannot GET /app3/cats',
}));
},
);
});

afterEach(async () => {
await Promise.all(apps.map(app => app.close()));
await adapter.close();
});
});*/
});
4 changes: 2 additions & 2 deletions packages/common/interfaces/http/http-server.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,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: 4 additions & 0 deletions packages/core/adapters/http-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,11 +92,15 @@ export abstract class AbstractHttpAdapter<
abstract redirect(response, statusCode: number, url: string);
abstract setErrorHandler(handler: Function, prefix?: string);
abstract setNotFoundHandler(handler: Function, prefix?: string);
abstract setRootNotFoundHandler(handler: Function);
abstract setHeader(response, name: string, value: string);
abstract registerParserMiddleware(prefix?: string);
abstract enableCors(options: CorsOptions, prefix?: string);
abstract createMiddlewareFactory(
requestMethod: RequestMethod,
): (path: string, callback: Function) => any;
abstract getType(): string;
abstract addNestInstanceBaseUrl(baseUrl?: string): void;
abstract getNotFoundCallback(baseUrl?: string);
abstract getRootNotFoundCallback();
}
9 changes: 5 additions & 4 deletions packages/core/nest-application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,8 @@ export class NestApplication extends NestApplicationContext

const useBodyParser =
this.appOptions && this.appOptions.bodyParser !== false;
useBodyParser && this.registerParserMiddleware();
useBodyParser &&
this.registerParserMiddleware(this.config.getGlobalPrefix());

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

public registerParserMiddleware() {
this.httpAdapter.registerParserMiddleware();
public registerParserMiddleware(prefix?: string) {
this.httpAdapter.registerParserMiddleware(prefix);
}

public async registerRouter() {
Expand Down Expand Up @@ -216,7 +217,7 @@ export class NestApplication extends NestApplicationContext
}

public enableCors(options?: CorsOptions): void {
this.httpAdapter.enableCors(options);
this.httpAdapter.enableCors(options, this.config.getGlobalPrefix());
}

public async listen(
Expand Down
20 changes: 15 additions & 5 deletions packages/core/router/routes-resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,15 +78,25 @@ export class RoutesResolver implements Resolver {

public registerNotFoundHandler() {
const applicationRef = this.container.getHttpAdapterRef();
const callback = <TRequest, TResponse>(req: TRequest, res: TResponse) => {
const method = applicationRef.getRequestMethod(req);
const url = applicationRef.getRequestUrl(req);
throw new NotFoundException(`Cannot ${method} ${url}`);
};
applicationRef.addNestInstanceBaseUrl(this.config.getGlobalPrefix());

const callback = applicationRef.getNotFoundCallback(
this.config.getGlobalPrefix(),
);
const handler = this.routerExceptionsFilter.create({}, callback, undefined);
const proxy = this.routerProxy.createProxy(callback, handler);
applicationRef.setNotFoundHandler &&
applicationRef.setNotFoundHandler(proxy, this.config.getGlobalPrefix());

const rootCallback = applicationRef.getRootNotFoundCallback();
const rootHandler = this.routerExceptionsFilter.create(
{},
rootCallback,
undefined,
);
const rootProxy = this.routerProxy.createProxy(rootCallback, rootHandler);
applicationRef.setRootNotFoundHandler &&
applicationRef.setRootNotFoundHandler(rootProxy);
}

public registerExceptionHandler() {
Expand Down
22 changes: 22 additions & 0 deletions packages/core/test/router/routes-resolver.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,28 @@ describe('RoutesResolver', () => {

describe('registerNotFoundHandler', () => {
it('should register not found handler', () => {
let applicationRef = {
addNestInstanceBaseUrl: (baseUrl: string) => {
return;
},
getNotFoundCallback: (baseUrl?: string) => {
return (req, res, next) => {
next();
};
},
getRootNotFoundCallback: () => {
return (req, res, next) => {
next();
};
},
setNotFoundHandler: sinon.spy(),
setRootNotFoundHandler: sinon.spy(),
};

sinon
.stub((routesResolver as any).container, 'getHttpAdapterRef')
.callsFake(() => applicationRef);

routesResolver.registerNotFoundHandler();

expect(applicationRef.setNotFoundHandler.called).to.be.true;
Expand Down
9 changes: 7 additions & 2 deletions packages/core/test/utils/noop-adapter.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { RequestMethod } from '@nestjs/common';
import { AbstractHttpAdapter } from '../../adapters';
import { Func } from 'mocha';

export class NoopHttpAdapter extends AbstractHttpAdapter {
constructor(instance: any) {
Expand All @@ -18,11 +19,15 @@ export class NoopHttpAdapter extends AbstractHttpAdapter {
redirect(response: any, statusCode: number, url: string) {}
setErrorHandler(handler: Function, prefix = '/'): any {}
setNotFoundHandler(handler: Function, prefix = '/'): any {}
setRootNotFoundHandler(handler: Function): 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 '';
}
addNestInstanceBaseUrl(baseUrl?: string): void {}
getNotFoundCallback(baseUrl?: string) {}
getRootNotFoundCallback() {}
}
Loading