Best JavaScript code snippet using redwood
chat.service.ts
Source: chat.service.ts
1import { Injectable, Logger } from '@nestjs/common';2import { Socket } from 'socket.io';3import { UserManager } from '../user/user.model';4import { ChanManager, ChanService } from './chan.service';5import { ChatCommandHandlers } from './chat.commands';67export class ClientIdentifier {8 sock: Socket;9 chan: string;10}1112export class ChatUsersManager {13 public static users: Map<string, ClientIdentifier> = new Map<string, ClientIdentifier>();14}1516@Injectable()17export class ChatService {18 // public users: Map<string, ClientIdentifier> = new Map<string, ClientIdentifier>();19 public users = ChatUsersManager.users;2021 constructor(private chanService: ChanService, private chatCommandHandlers: ChatCommandHandlers) {22 chanService.chatService = this;23 }2425 getUsers(): Map<string, ClientIdentifier> {26 return this.users;27 }2829 private getUserFromSocket(sock: Socket): string {30 for (let [key, value] of this.users) {31 if (value.sock == sock)32 return key;33 }34 return null;35 }3637 async execute(name: string, msg: string, client: Socket) {3839 let uname = this.getUserFromSocket(client);40 if (uname == null)41 return;4243 if (msg.length > 250) {44 client.emit("recv_message", { name: "", msg: "Message too long. You will be disconnected", isCommandResponse: true });45 client.disconnect(true);46 return;47 }4849 const Arr = msg.split(" ");5051 const commands = {52 "/ping": this.chatCommandHandlers.pingCommand,53 "/help": this.chatCommandHandlers.helpCommand,54 "/chans": this.chatCommandHandlers.chansCommand,55 "/users": this.chatCommandHandlers.usersCommand,56 "/op": this.chatCommandHandlers.opCommand,57 "/block": this.chatCommandHandlers.blockCommand,58 "/unblock": this.chatCommandHandlers.unblockCommand,59 "/pm": this.chatCommandHandlers.pmCommand,60 "/cchan": this.chatCommandHandlers.cchanCommand,61 "/dchan": this.chatCommandHandlers.dchanCommand,62 "/join": this.chatCommandHandlers.joinCommand,63 "/kick": this.chatCommandHandlers.kickCommand,64 "/ban": this.chatCommandHandlers.muteCommand,65 "/mute": this.chatCommandHandlers.muteCommand,66 "/unmute": this.chatCommandHandlers.unmuteCommand,67 "/unban": this.chatCommandHandlers.unmuteCommand,68 "/leave": this.chatCommandHandlers.leaveCommand,69 "/passwd": this.chatCommandHandlers.passwdCommand,70 "/rmpasswd": this.chatCommandHandlers.passwdCommand71 }7273 if (Arr[0] in commands) {74 const data = await commands[Arr[0]](client, Arr, uname, this.users, this.chanService);75 if (Arr[0] !== "/pm")76 client.emit("recv_message", { ...data, isCommandResponse: true })7778 } else if (Arr[0].startsWith('/')) {79 client.emit("recv_message", { name: "", msg: "Command not found.", isCommandResponse: true })80 } else {81 const c = this.users.get(uname).chan;82 const banData = await this.chanService.checkban(c, uname);83 const muteData = await this.chanService.checkmute(c, uname);8485 if (banData && !banData.expired()) {86 name = "";87 msg = 'You are banned from this channel ' + banData.getFormattedTime() + '.\nReason: "' + banData.reason + '".';88 client.emit('recv_message', { name, msg, isCommandResponse: true });89 return;90 }91 if (muteData && !muteData.expired()) {92 name = "";93 msg = 'You are muted from this channel ' + muteData.getFormattedTime() + '.\nReason: "' + muteData.reason + '".';94 client.emit('recv_message', { name, msg, isCommandResponse: true });95 return;96 }9798 const cusers = this.chanService.getUsers(c).sort((a, b) => a.localeCompare(b));99 const where = cusers.map(x => { return { id: x }});100 let db_cusers = await UserManager.instance.userRepository.find({where});101 db_cusers.sort((a, b) => a.id.localeCompare(b.id))102 if (!db_cusers) {103 client.emit('recv_message', { name: "", msg: "Unexpected error", isCommandResponse: true });104 return;105 }106107 for (let index = 0; index < cusers.length; index++) {108 const toBanData = await this.chanService.checkban(c, cusers[index]);109 if (!db_cusers[index].isBlocking(uname) && (!toBanData || toBanData.expired())) {110 this.users.get(cusers[index]).sock.emit('recv_message', { name, msg, isCommandResponse: false });111 }112 }113 }114 }115116 async addClient(uname: string, client: Socket) {117 let user = await UserManager.instance.userRepository.findOne({ where: { id: uname } });118 if (!user) {119 client.disconnect();120 return;121 }122 if (!ChanManager.instance.chans.find(x => user.chatLastChannel == x.name)) {123 user.chatLastChannel = "general";124 await UserManager.instance.userRepository.save(user);125 }126 try {127 await this.chanService.join(client, user.chatLastChannel, uname, null, true);128 this.users.set(uname, {129 sock: client,130 chan: user.chatLastChannel,131 });132 client.emit('recv_message', { name: "", msg: "Type /help to display command information.", isCommandResponse: true });133 await this.chanService.join(client, user.chatLastChannel, uname);134 } catch (err) {135 this.users.set(uname, {136 sock: client,137 chan: 'general',138 });139 await this.chanService.join(client, 'general', uname);140 client.emit('recv_message', { name: "", msg: "Type /help to display command information.", isCommandResponse: true });141 user.chatLastChannel = 'general';142 await UserManager.instance.userRepository.save(user);143 }144 }145146 rmClient(client: Socket) {147 let uname = this.getUserFromSocket(client);148 if (uname != null) {149 this.chanService.leave(this.users.get(uname).chan, uname);150 this.users.delete(uname);151 }152 }
...
messages.js
Source: messages.js
...79 function message(msgclz, msg, target, exclude) {80 if (!target)81 return;82 if (target.recv_message && typeof target.recv_message === 'function')83 target.recv_message(msgclz, msg, exclude);84 else if (target instanceof fm.ROOM) {85 for ( var id in target.contains) {86 var ob = target.contains[id];87 if (ob && exclude)88 if (ob === exclude || 89 (exclude instanceof Array && exclude.indexOf(ob) >= 0))90 continue;91 if (ob.recv_message && typeof ob.recv_message === 'function')92 ob.recv_message(msgclz, msg);93 }94 }95 }...
reducers.spec.js
Source: reducers.spec.js
1import {expect} from 'chai';2import {RECV_MESSAGE} from '../app/actions';3import reducer from '../app/reducers/messages';4describe('message reducer', () => {5 it('should return the initial state', () => {6 expect(reducer(undefined, {})).to.eql([]);7 });8 it('should handle RECV_MESSAGE', () => {9 const firstMessageText = "Hello World!";10 expect(11 reducer([], {12 type: RECV_MESSAGE,13 message: firstMessageText14 })15 ).to.eql([firstMessageText]);16 const secondMessageText = 'cow';17 const seededStateArray = ['how', 'now', 'brown'];18 expect(19 reducer(seededStateArray, {20 type: RECV_MESSAGE,21 message: secondMessageText22 })23 ).to.eql([...seededStateArray, secondMessageText]);24 });...
Check out the latest blogs from LambdaTest on this topic:
Have you ever struggled with handling hidden elements while automating a web or mobile application? I was recently automating an eCommerce application. I struggled with handling hidden elements on the web page.
In today’s data-driven world, the ability to access and analyze large amounts of data can give researchers, businesses & organizations a competitive edge. One of the most important & free sources of this data is the Internet, which can be accessed and mined through web scraping.
Dries Buytaert, a graduate student at the University of Antwerp, came up with the idea of developing something similar to a chat room. Moreover, he modified the conventional chat rooms into a website where his friends could post their queries and reply through comments. However, for this project, he thought of creating a temporary archive of posts.
The QA testing profession requires both educational and long-term or experience-based learning. One can learn the basics from certification courses and exams, boot camp courses, and college-level courses where available. However, developing instinctive and practical skills works best when built with work experience.
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!!