Skip to content

Commit

Permalink
feature(websockets) extract web sockets drivers
Browse files Browse the repository at this point in the history
  • Loading branch information
kamilmysliwiec committed Dec 12, 2018
1 parent 03b0cf8 commit 53687ba
Show file tree
Hide file tree
Showing 59 changed files with 616 additions and 371 deletions.
8 changes: 7 additions & 1 deletion gulpfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ const packages = {
'platform-fastify': ts.createProject(
'packages/platform-fastify/tsconfig.json',
),
'platform-socket.io': ts.createProject(
'packages/platform-socket.io/tsconfig.json',
),
'platform-ws': ts.createProject('packages/platform-ws/tsconfig.json'),
};
const modules = Object.keys(packages);
const source = 'packages';
Expand All @@ -42,7 +46,9 @@ gulp.task('copy-misc', function() {
.pipe(gulp.dest(`${source}/websockets`))
.pipe(gulp.dest(`${source}/testing`))
.pipe(gulp.dest(`${source}/platform-fastify`))
.pipe(gulp.dest(`${source}/platform-express`));
.pipe(gulp.dest(`${source}/platform-express`))
.pipe(gulp.dest(`${source}/platform-ws`))
.pipe(gulp.dest(`${source}/platform-socket.io`));
});

gulp.task('clean:output', function() {
Expand Down
13 changes: 8 additions & 5 deletions integration/hello-world/e2e/fastify-adapter.spec.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
import { INestApplication } from '@nestjs/common';
import { INestFastifyApplication } from '@nestjs/common/interfaces/nest-fastify-application.interface';
import { FastifyAdapter } from '@nestjs/platform-fastify';
import {
FastifyAdapter,
INestFastifyApplication,
} from '@nestjs/platform-fastify';
import { Test } from '@nestjs/testing';
import { expect } from 'chai';
import { ApplicationModule } from '../src/app.module';

describe('Hello world (fastify adapter)', () => {
let app: INestApplication & INestFastifyApplication;
let app: INestFastifyApplication;

beforeEach(async () => {
const module = await Test.createTestingModule({
imports: [ApplicationModule],
}).compile();

app = module.createNestApplication(new FastifyAdapter());
app = module.createNestApplication<INestFastifyApplication>(
new FastifyAdapter(),
);
await app.init();
});

Expand Down
30 changes: 18 additions & 12 deletions integration/hello-world/e2e/interceptors.spec.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,30 @@
import * as request from 'supertest';
import { Test } from '@nestjs/testing';
import { INestApplication, Injectable } from '@nestjs/common';
import { ApplicationModule } from '../src/app.module';
import {
CallHandler,
ExecutionContext,
INestApplication,
Injectable,
NestInterceptor,
} from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { Test } from '@nestjs/testing';
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
import * as request from 'supertest';
import { ApplicationModule } from '../src/app.module';

const RETURN_VALUE = 'test';

@Injectable()
export class OverrideInterceptor {
intercept(context, stream) {
export class OverrideInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler) {
return of(RETURN_VALUE);
}
}

@Injectable()
export class TransformInterceptor {
intercept(context, stream) {
return stream.pipe(map(data => ({ data })));
intercept(context: ExecutionContext, next: CallHandler) {
return next.handle().pipe(map(data => ({ data })));
}
}

Expand All @@ -41,7 +47,7 @@ describe('Interceptors', () => {
app = (await createTestModule(
new OverrideInterceptor(),
)).createNestApplication();

await app.init();
return request(app.getHttpServer())
.get('/hello')
Expand All @@ -52,7 +58,7 @@ describe('Interceptors', () => {
app = (await createTestModule(
new TransformInterceptor(),
)).createNestApplication();

await app.init();
return request(app.getHttpServer())
.get('/hello')
Expand All @@ -63,7 +69,7 @@ describe('Interceptors', () => {
app = (await createTestModule(
new TransformInterceptor(),
)).createNestApplication();

await app.init();
return request(app.getHttpServer())
.get('/hello/stream')
Expand All @@ -74,7 +80,7 @@ describe('Interceptors', () => {
app = (await createTestModule(
new TransformInterceptor(),
)).createNestApplication();

await app.init();
return request(app.getHttpServer())
.get('/hello/async')
Expand Down
1 change: 0 additions & 1 deletion integration/websockets/e2e/gateway.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ async function createNestApp(...gateways): Promise<INestApplication> {
}

describe('WebSocketGateway', () => {
const event = 'push';
let ws, app;

it(`should handle message (2nd port)`, async () => {
Expand Down
2 changes: 1 addition & 1 deletion integration/websockets/e2e/ws-gateway.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { INestApplication } from '@nestjs/common';
import { WsAdapter } from '@nestjs/platform-ws';
import { Test } from '@nestjs/testing';
import { WsAdapter } from '@nestjs/websockets/adapters/ws-adapter';
import { expect } from 'chai';
import * as WebSocket from 'ws';
import { ApplicationGateway } from '../src/app.gateway';
Expand Down
63 changes: 14 additions & 49 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@
"sinon-chai": "^2.8.0",
"socket.io-client": "^2.0.4",
"supertest": "^3.0.0",
"ts-node": "^6.0.0",
"ts-node": "^7.0.1",
"tslint": "^5.11.0",
"typescript": "^3.2.2"
},
Expand Down
1 change: 1 addition & 0 deletions packages/common/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export {
ValidationError,
WebSocketAdapter,
WsExceptionFilter,
WsMessageHandler,
} from './interfaces';
export * from './pipes';
export * from './serializer';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
import { Observable } from 'rxjs';

export interface WebSocketAdapter<T = any> {
create(port: number, options?: T): any;
bindClientConnect(server: any, callback: (...args: any[]) => void): any;
bindClientDisconnect?(client: any, callback: (...args: any[]) => void): any;
export interface WsMessageHandler<T = string> {
message: T;
callback: (...args: any[]) => Observable<any> | Promise<any>;
}
export interface WebSocketAdapter<
TServer = any,
TClient = any,
TOptions = any
> {
create(port: number, options?: TOptions): TServer;
bindClientConnect(server: TServer, callback: Function): any;
bindClientDisconnect?(client: TClient, callback: Function): any;
bindMessageHandlers(
client: any,
handlers: Array<{
message: any;
callback: (...args: any[]) => Observable<any> | Promise<any> | any;
}>,
client: TClient,
handlers: WsMessageHandler[],
transform: (data: any) => Observable<any>,
): any;
close(server: any): any;
close(server: TServer): any;
}
14 changes: 9 additions & 5 deletions packages/core/adapters/http-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,12 @@ import { RequestHandler } from '@nestjs/common/interfaces';
import { CorsOptions } from '@nestjs/common/interfaces/external/cors-options.interface';
import { NestApplicationOptions } from '@nestjs/common/interfaces/nest-application-options.interface';

export abstract class AbstractHttpAdapter<T = any> implements HttpServer {
protected httpServer: T;
export abstract class AbstractHttpAdapter<
TServer = any,
TRequest = any,
TResponse = any
> implements HttpServer<TRequest, TResponse> {
protected httpServer: TServer;

constructor(protected readonly instance: any) {}

Expand Down Expand Up @@ -60,11 +64,11 @@ export abstract class AbstractHttpAdapter<T = any> implements HttpServer {
return this.instance.listen(port, hostname, callback);
}

public getHttpServer(): T {
return this.httpServer as T;
public getHttpServer(): TServer {
return this.httpServer as TServer;
}

public setHttpServer(httpServer: T) {
public setHttpServer(httpServer: TServer) {
this.httpServer = httpServer;
}

Expand Down
4 changes: 2 additions & 2 deletions packages/core/exceptions/exceptions-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,12 @@ export class ExceptionsHandler extends BaseExceptionFilter {
if (isEmpty(this.filters)) return false;

const filter = this.filters.find(({ exceptionMetatypes }) => {
const hasMetatype =
const typeExists =
!exceptionMetatypes.length ||
exceptionMetatypes.some(
ExceptionMetatype => exception instanceof ExceptionMetatype,
);
return hasMetatype;
return typeExists;
});
filter && filter.func(exception, ctx);
return !!filter;
Expand Down
2 changes: 1 addition & 1 deletion packages/core/guards/guards-consumer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { CanActivate } from '@nestjs/common';
import { Controller } from '@nestjs/common/interfaces';
import { isEmpty } from '@nestjs/common/utils/shared.utils';
import { Observable } from 'rxjs';
import { ExecutionContextHost } from '../helpers/execution-context.host';
import { ExecutionContextHost } from '../helpers/execution-context-host';

export class GuardsConsumer {
public async tryActivate(
Expand Down
18 changes: 18 additions & 0 deletions packages/core/helpers/load-adapter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Logger } from '@nestjs/common';

const MISSING_REQUIRED_DEPENDENCY = (
defaultPlatform: string,
transport: string,
) =>
`No driver (${transport}) has been selected. In order to take advantage of the default driver, please, ensure to install the "${defaultPlatform}" package ($ npm install ${defaultPlatform}).`;

const logger = new Logger('PackageLoader');

export function loadAdapter(defaultPlatform: string, transport: string) {
try {
return require(defaultPlatform);
} catch (e) {
logger.error(MISSING_REQUIRED_DEPENDENCY(defaultPlatform, transport));
process.exit(1);
}
}
2 changes: 1 addition & 1 deletion packages/core/interceptors/interceptors-consumer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { CallHandler, Controller } from '@nestjs/common/interfaces';
import { isEmpty } from '@nestjs/common/utils/shared.utils';
import { defer, from as fromPromise, Observable } from 'rxjs';
import { mergeAll, switchMap } from 'rxjs/operators';
import { ExecutionContextHost } from '../helpers/execution-context.host';
import { ExecutionContextHost } from '../helpers/execution-context-host';

export class InterceptorsConsumer {
public async intercept(
Expand Down
Loading

0 comments on commit 53687ba

Please sign in to comment.