@nestjs/websockets
Version:
WebSockets for NestJS: gateways with message handlers, guards, pipes and interceptors, on Socket.IO or ws.
62 lines (61 loc) • 2.28 kB
JavaScript
import { NestApplication, NestApplicationContext } from '@nestjs/core';
import { CONNECTION_EVENT, DISCONNECT_EVENT } from '../constants.js';
import { isFunction } from '@nestjs/common/internal';
export class AbstractWsAdapter {
httpServer;
_forceCloseConnections;
set forceCloseConnections(value) {
this._forceCloseConnections = value;
}
get forceCloseConnections() {
return this._forceCloseConnections;
}
constructor(appOrHttpServer) {
if (appOrHttpServer && appOrHttpServer instanceof NestApplication) {
this.httpServer = appOrHttpServer.getUnderlyingHttpServer();
}
else if (appOrHttpServer instanceof NestApplicationContext) {
// An application without an HTTP server, e.g. a standalone microservice
this.httpServer = undefined;
}
else {
this.httpServer = appOrHttpServer;
}
}
bindClientConnect(server, callback) {
server.on(CONNECTION_EVENT, callback);
}
bindClientDisconnect(client, callback) {
if (typeof client.once === 'function') {
client.once(DISCONNECT_EVENT, callback);
return;
}
client.on(DISCONNECT_EVENT, callback);
}
/**
* Drops a client that connected while the lifecycle hooks of the application
* ("onModuleInit", "onApplicationBootstrap") were still running. Neither the
* connection hook of the gateway nor its message handlers were bound to this
* client, so it is expected to connect again.
*/
closeClient(client) {
const target = client;
if (isFunction(target.terminate)) {
// ws: there is no closing handshake to wait for
target.terminate();
}
else if (isFunction(target.conn?.close)) {
// socket.io: closing the underlying connection, unlike "disconnect()",
// lets the client reconnect by itself
target.conn.close();
}
else if (isFunction(target.close)) {
target.close();
}
}
async close(server) {
const isCallable = server && isFunction(server.close);
isCallable && (await new Promise(resolve => server.close(resolve)));
}
async dispose() { }
}