Best JavaScript code snippet using best
events.gateway.ts
Source:events.gateway.ts
1import {2 SubscribeMessage,3 WebSocketGateway,4 WebSocketServer5} from '@nestjs/websockets';6import { Server, Socket } from 'socket.io';7import { Logger, Injectable } from '@nestjs/common';8import { ActionTypes, FormData } from '@poc/api-interfaces';9@WebSocketGateway()10//@Injectable()11export class EventsGateway {12 connectedClients = [];13 data = {};14 @WebSocketServer()15 server: Server;16 @WebSocketServer()17 logServer: Server;18 private logger: Logger = new Logger('EventsGateway');19 handleConnection(client: Socket) {20 this.connectedClients = [...this.connectedClients, client.id];21 this.logger.log(22 `Client connected: ${client.id} - ${this.connectedClients.length} connected clients.`23 );24 //this.server.emit(ActionTypes.ClientConnected, this.connectedClients);25 //this.server.emit(ActionTypes.Data, this.data);26 client.emit(ActionTypes.Data, this.data);27 }28 handleDisconnect(client: Socket) {29 this.connectedClients = this.connectedClients.filter(30 connectedClient => connectedClient !== client.id31 );32 this.logger.log(33 `Client disconnected: ${client.id} - ${this.connectedClients.length} connected clients.`34 );35 this.server.emit(ActionTypes.ClientConnected, this.connectedClients);36 this.logServer.emit(ActionTypes.ClientConnected, this.connectedClients);37 }38 @SubscribeMessage(ActionTypes.PatchValue)39 patchValue(client: Socket, payload: Partial<FormData>) {40 this.data = { ...this.data, ...payload };41 this.logger.log(`Patch value: ${JSON.stringify(payload)}.`);42 client.broadcast.emit(ActionTypes.ValuePatched, payload);43 }44 postLogs(data: any){45 this.logServer.emit(ActionTypes.Data, data);46 }47 postData(data: any){48 this.server.emit(ActionTypes.Data, data);49 }...
messages-ws.service.ts
Source:messages-ws.service.ts
1import { Injectable } from '@nestjs/common';2import { Socket } from 'socket.io';3import { User } from '../auth/entities/user.entity';4import { Repository } from 'typeorm';5import { InjectRepository } from '@nestjs/typeorm';6interface ConnectedClients {7 [id: string]: {8 socket: Socket,9 user: User10 }11}12@Injectable()13export class MessagesWsService {14 private connectedClients: ConnectedClients = {}15 constructor (16 @InjectRepository(User)17 private readonly userRepository: Repository<User>18 ) {}19 async registerCliente( client: Socket, userId: string ) {20 21 const user = await this.userRepository.findOneBy({ id: userId })22 if ( !user ) throw new Error('User not found');23 if ( !user.isActive ) throw new Error('User not active');24 this.checkUserConnection( user );25 this.connectedClients[client.id] = {26 socket: client,27 user: user,28 };29 }30 removeCliente( clientId: string ) {31 delete this.connectedClients[clientId];32 }33 getConnectedClients(): string [] {34 return Object.keys( this.connectedClients);35 }36 getUserFullName( socketId: string ){37 return this.connectedClients[socketId].user.fullName;38 }39 private checkUserConnection(user: User) {40 for (const clientId of Object.keys( this.connectedClients )) {41 const connectedClient = this.connectedClients[clientId];42 if ( connectedClient.user.id === user.id ){43 connectedClient.socket.disconnect();44 break;45 }46 }47 }...
index.js
Source:index.js
1const io = require('socket.io');2const server = io.listen(8000);3console.log('Server socket is listening on port 8000');4let connectedClients = new Map();5var previousMessages = require('./src/previousMessages.json');67// event fired every time a new client connects8server.on('connection', socket => {9 console.info(`Client connected [id=${socket.id}]`);10 connectedClients.set(socket.id, socket);11 console.log(connectedClients.size + ' client/s connected');12 sendPreviousMessages(socket);1314 // when socket disconnects, remove it from the map15 socket.on('disconnect', () => {16 connectedClients.delete(socket.id);17 console.info(`Client [id=${socket.id}] disconnected`);18 console.log(connectedClients.size + ' client/s connected');19 });2021 socket.on('chat', payload => {22 sendMessageToAllOtherClients(socket, payload);23 });24});2526function sendMessageToAllOtherClients(sender, message) {27 for (let [key, socket] of connectedClients) {28 socket.emit('message-from-server', { id: sender.id, message: new Date().toUTCString() + ": " + message});29 }30 saveMessageInJSON(sender, message );31}32function sendPreviousMessages(socket) {33 for( let previousMessage of previousMessages ){34 socket.emit( 'message-from-server', previousMessage);35 }36}3738function saveMessageInJSON(sender, message) {39 previousMessages[previousMessages.length] = {id: sender.id, message: new Date().toUTCString() + ": " + message};
...
Using AI Code Generation
1var BestPeer = require('./BestPeer.js');2var bp = new BestPeer();3var connectedClients = bp.connectedClients();4console.log(connectedClients);5var connectedClients = function(){6 return "Connected Clients";7}8module.exports = BestPeer;9var bp = require('./BestPeer.js');10var connectedClients = bp.connectedClients();11console.log(connectedClients);12var BestPeer = function(){13 this.connectedClients = function(){14 return "Connected Clients";15 }16}17module.exports = BestPeer;18var bp = require('./BestPeer.js');19var connectedClients = bp.connectedClients();20console.log(connectedClients);21var BestPeer = function(){22 this.connectedClients = function(){23 return "Connected Clients";24 }25}26module.exports = BestPeer;27exports.connectedClients = function(){28 return "Connected Clients";29}
Using AI Code Generation
1var BestPractices = require('best-practices');2var bp = new BestPractices();3var clients = bp.connectedClients();4console.log(clients);5var BestPractices = require('best-practices');6var bp = new BestPractices();7var clients = bp.connectedClients();8console.log(clients);9var BestPractices = require('best-practices');10var bp = new BestPractices();11var clients = bp.connectedClients();12console.log(clients);13var BestPractices = require('best-practices');14var bp = new BestPractices();15var clients = bp.connectedClients();16console.log(clients);17var BestPractices = require('best-practices');18var bp = new BestPractices();19var clients = bp.connectedClients();20console.log(clients);21var BestPractices = require('best-practices');22var bp = new BestPractices();23var clients = bp.connectedClients();24console.log(clients);25var BestPractices = require('best-practices');26var bp = new BestPractices();27var clients = bp.connectedClients();28console.log(clients);29var BestPractices = require('best-practices');30var bp = new BestPractices();31var clients = bp.connectedClients();32console.log(clients);33var BestPractices = require('best-practices');
Using AI Code Generation
1var BestPeer = require('bestpeer');2var bp = new BestPeer();3var connectedPeers = bp.connectedClients();4console.log(connectedPeers);5bp.sendToAllPeers("Hello World");6bp.sendToPeer("Hello World", "
Using AI Code Generation
1var bp = require('bestpeer');2var bpClient = new bp.BestPeerClient();3bpClient.connect(function(err) {4 if (err) {5 console.log("Error connecting to BestPeer");6 return;7 }8 bpClient.connectedClients(function(err, clients) {9 if (err) {10 console.log("Error getting connected clients");11 return;12 }13 console.log("Connected clients: " + clients);14 bpClient.sendToAll("Hello from node.js", function(err) {15 if (err) {16 console.log("Error sending message");17 return;18 }19 console.log("Message sent successfully");20 });21 });22});23var bp = require('bestpeer');24var bpClient = new bp.BestPeerClient();25bpClient.connect(function(err) {26 if (err) {27 console.log("Error connecting to BestPeer");28 return;29 }30 bpClient.sendToAll("Hello from node.js", function(err) {31 if (err) {32 console.log("Error sending message");33 return;34 }35 console.log("Message sent successfully");36 });37});38var bp = require('bestpeer');39var bpClient = new bp.BestPeerClient();40bpClient.connect(function(err) {41 if (err) {42 console.log("Error connecting to BestPeer");43 return;44 }45 bpClient.sendTo("Client1", "Hello from node.js", function(err) {46 if (err) {47 console.log("Error sending message");48 return;49 }50 console.log("Message sent successfully");51 });52});53var bp = require('bestpeer');54var bpClient = new bp.BestPeerClient();55bpClient.connect(function(err) {
Using AI Code Generation
1var BestHTTP = require("best-http");2var http = new BestHTTP();3http.connectedClients(function(err, data){4 if(err){5 console.log("Error: " + err);6 } else {7 console.log("Number of clients connected: " + data);8 }9});10var BestHTTP = require("best-http");11var http = new BestHTTP();12http.connectedClients()13 .then(function(data){14 console.log("Number of clients connected: " + data);15 })16 .catch(function(err){17 console.log("Error: " + err);18 });19var BestHTTP = require("best-http");20var http = new BestHTTP();21async function run(){22 try{23 var data = await http.connectedClients();24 console.log("Number of clients connected: " + data);25 } catch(err){26 console.log("Error: " + err);27 }28}29run();30var BestHTTP = require("best-http");31var http = new BestHTTP();32(async function(){33 try{34 var data = await http.connectedClients();35 console.log("Number of clients connected: " + data);36 } catch(err){37 console.log("Error: " + err);38 }39})();40var BestHTTP = require("best-http");41var http = new BestHTTP();42(async () => {43 try{44 var data = await http.connectedClients();45 console.log("Number of clients connected: " + data);46 } catch(err){47 console.log("Error: " + err);48 }49})();
Using AI Code Generation
1var bp = require('bestpeer');2bp.connectToServer( function(){3 bp.connectedClients( function(clients){4 console.log("Connected clients: ");5 console.log(clients);6 });7});8var bp = require('bestpeer');9bp.connectToServer( function(){10 bp.addFile("test.txt", function(files){11 console.log("Files: ");12 console.log(files);13 });14});15var bp = require('bestpeer');16bp.connectToServer( function(){17 bp.removeFile("test.txt", function(files){18 console.log("Files: ");19 console.log(files);20 });21});22var bp = require('bestpeer');23bp.connectToServer( function(){24 bp.files( function(files){25 console.log("Files: ");26 console.log(files);27 });28});29var bp = require('bestpeer');30bp.connectToServer( function(){31 bp.findFile("test.txt", function(clients){32 console.log("Clients with file: ");33 console.log(clients);34 });35});
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!