Turning let into const where applicable

This commit is contained in:
David Négrier 2020-06-09 15:54:54 +02:00
parent 30ca47c2d8
commit ac0b7a7361
5 changed files with 54 additions and 54 deletions

View file

@ -16,15 +16,15 @@ export class AuthenticateController {
login(){ login(){
// For now, let's completely forget the /login route. // For now, let's completely forget the /login route.
this.App.post("/login", (req: Request, res: Response) => { this.App.post("/login", (req: Request, res: Response) => {
let param = req.body; const param = req.body;
/*if(!param.name){ /*if(!param.name){
return res.status(BAD_REQUEST).send({ return res.status(BAD_REQUEST).send({
message: "email parameter is empty" message: "email parameter is empty"
}); });
}*/ }*/
//TODO check user email for The Coding Machine game //TODO check user email for The Coding Machine game
let userId = uuid(); const userId = uuid();
let token = Jwt.sign({name: param.name, userId: userId}, SECRET_KEY, {expiresIn: '24h'}); const token = Jwt.sign({name: param.name, userId: userId}, SECRET_KEY, {expiresIn: '24h'});
return res.status(OK).send({ return res.status(OK).send({
token: token, token: token,
mapUrlStart: URL_ROOM_STARTED, mapUrlStart: URL_ROOM_STARTED,

View file

@ -79,9 +79,9 @@ export class IoSocketController {
* @param token * @param token
*/ */
searchClientByToken(token: string): ExSocketInterface | null { searchClientByToken(token: string): ExSocketInterface | null {
let clients: Array<any> = Object.values(this.Io.sockets.sockets); const clients: Array<any> = Object.values(this.Io.sockets.sockets);
for (let i = 0; i < clients.length; i++) { for (let i = 0; i < clients.length; i++) {
let client: ExSocketInterface = clients[i]; const client: ExSocketInterface = clients[i];
if (client.token !== token) { if (client.token !== token) {
continue continue
} }
@ -93,9 +93,9 @@ export class IoSocketController {
private sendUpdateGroupEvent(group: Group): void { private sendUpdateGroupEvent(group: Group): void {
// Let's get the room of the group. To do this, let's get anyone in the group and find its room. // Let's get the room of the group. To do this, let's get anyone in the group and find its room.
// Note: this is suboptimal // Note: this is suboptimal
let userId = group.getUsers()[0].id; const userId = group.getUsers()[0].id;
let client: ExSocketInterface = this.searchClientByIdOrFail(userId); const client: ExSocketInterface = this.searchClientByIdOrFail(userId);
let roomId = client.roomId; const roomId = client.roomId;
this.Io.in(roomId).emit(SockerIoEvent.GROUP_CREATE_UPDATE, { this.Io.in(roomId).emit(SockerIoEvent.GROUP_CREATE_UPDATE, {
position: group.getPosition(), position: group.getPosition(),
groupId: group.getId() groupId: group.getId()
@ -104,19 +104,19 @@ export class IoSocketController {
private sendDeleteGroupEvent(uuid: string, lastUser: UserInterface): void { private sendDeleteGroupEvent(uuid: string, lastUser: UserInterface): void {
// Let's get the room of the group. To do this, let's get anyone in the group and find its room. // Let's get the room of the group. To do this, let's get anyone in the group and find its room.
let userId = lastUser.id; const userId = lastUser.id;
let client: ExSocketInterface = this.searchClientByIdOrFail(userId); const client: ExSocketInterface = this.searchClientByIdOrFail(userId);
let roomId = client.roomId; const roomId = client.roomId;
this.Io.in(roomId).emit(SockerIoEvent.GROUP_DELETE, uuid); this.Io.in(roomId).emit(SockerIoEvent.GROUP_DELETE, uuid);
} }
ioConnection() { ioConnection() {
this.Io.on(SockerIoEvent.CONNECTION, (socket: Socket) => { this.Io.on(SockerIoEvent.CONNECTION, (socket: Socket) => {
let client : ExSocketInterface = socket as ExSocketInterface; const client : ExSocketInterface = socket as ExSocketInterface;
this.sockets.set(client.userId, client); this.sockets.set(client.userId, client);
// Let's log server load when a user joins // Let's log server load when a user joins
let srvSockets = this.Io.sockets.sockets; const srvSockets = this.Io.sockets.sockets;
this.nbClientsGauge.inc({ host: os.hostname() }); this.nbClientsGauge.inc({ host: os.hostname() });
console.log(new Date().toISOString() + ' A user joined (', Object.keys(srvSockets).length, ' connected users)'); console.log(new Date().toISOString() + ' A user joined (', Object.keys(srvSockets).length, ' connected users)');
si.currentLoad().then(data => console.log(' Current load: ', data.avgload)); si.currentLoad().then(data => console.log(' Current load: ', data.avgload));
@ -133,19 +133,19 @@ export class IoSocketController {
*/ */
socket.on(SockerIoEvent.JOIN_ROOM, (message: any, answerFn): void => { socket.on(SockerIoEvent.JOIN_ROOM, (message: any, answerFn): void => {
try { try {
let roomId = message.roomId; const roomId = message.roomId;
if (typeof(roomId) !== 'string') { if (typeof(roomId) !== 'string') {
socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: 'Expected roomId as a string.'}); socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: 'Expected roomId as a string.'});
return; return;
} }
let position = this.hydratePositionReceive(message.position); const position = this.hydratePositionReceive(message.position);
if (position instanceof Error) { if (position instanceof Error) {
socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: position.message}); socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: position.message});
return; return;
} }
let Client = (socket as ExSocketInterface); const Client = (socket as ExSocketInterface);
if (Client.roomId === roomId) { if (Client.roomId === roomId) {
return; return;
@ -155,18 +155,18 @@ export class IoSocketController {
this.leaveRoom(Client); this.leaveRoom(Client);
//join new previous room //join new previous room
let world = this.joinRoom(Client, roomId, position); const world = this.joinRoom(Client, roomId, position);
//add function to refresh position user in real time. //add function to refresh position user in real time.
//this.refreshUserPosition(Client); //this.refreshUserPosition(Client);
let messageUserJoined = new MessageUserJoined(Client.userId, Client.name, Client.character, Client.position); const messageUserJoined = new MessageUserJoined(Client.userId, Client.name, Client.character, Client.position);
socket.to(roomId).emit(SockerIoEvent.JOIN_ROOM, messageUserJoined); socket.to(roomId).emit(SockerIoEvent.JOIN_ROOM, messageUserJoined);
// The answer shall contain the list of all users of the room with their positions: // The answer shall contain the list of all users of the room with their positions:
let listOfUsers = Array.from(world.getUsers(), ([key, user]) => { const listOfUsers = Array.from(world.getUsers(), ([key, user]) => {
let player = this.searchClientByIdOrFail(user.id); const player = this.searchClientByIdOrFail(user.id);
return new MessageUserPosition(user.id, player.name, player.character, player.position); return new MessageUserPosition(user.id, player.name, player.character, player.position);
}); });
answerFn(listOfUsers); answerFn(listOfUsers);
@ -178,19 +178,19 @@ export class IoSocketController {
socket.on(SockerIoEvent.USER_POSITION, (message: any): void => { socket.on(SockerIoEvent.USER_POSITION, (message: any): void => {
try { try {
let position = this.hydratePositionReceive(message); const position = this.hydratePositionReceive(message);
if (position instanceof Error) { if (position instanceof Error) {
socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: position.message}); socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: position.message});
return; return;
} }
let Client = (socket as ExSocketInterface); const Client = (socket as ExSocketInterface);
// sending to all clients in room except sender // sending to all clients in room except sender
Client.position = position; Client.position = position;
// update position in the world // update position in the world
let world = this.Worlds.get(Client.roomId); const world = this.Worlds.get(Client.roomId);
if (!world) { if (!world) {
console.error("Could not find world with id '", Client.roomId, "'"); console.error("Could not find world with id '", Client.roomId, "'");
return; return;
@ -206,7 +206,7 @@ export class IoSocketController {
socket.on(SockerIoEvent.WEBRTC_SIGNAL, (data: any) => { socket.on(SockerIoEvent.WEBRTC_SIGNAL, (data: any) => {
//send only at user //send only at user
let client = this.sockets.get(data.receiverId); const client = this.sockets.get(data.receiverId);
if (client === undefined) { if (client === undefined) {
console.warn("While exchanging a WebRTC signal: client with id ", data.receiverId, " does not exist. This might be a race condition."); console.warn("While exchanging a WebRTC signal: client with id ", data.receiverId, " does not exist. This might be a race condition.");
return; return;
@ -216,7 +216,7 @@ export class IoSocketController {
socket.on(SockerIoEvent.WEBRTC_OFFER, (data: any) => { socket.on(SockerIoEvent.WEBRTC_OFFER, (data: any) => {
//send only at user //send only at user
let client = this.sockets.get(data.receiverId); const client = this.sockets.get(data.receiverId);
if (client === undefined) { if (client === undefined) {
console.warn("While exchanging a WebRTC offer: client with id ", data.receiverId, " does not exist. This might be a race condition."); console.warn("While exchanging a WebRTC offer: client with id ", data.receiverId, " does not exist. This might be a race condition.");
return; return;
@ -225,7 +225,7 @@ export class IoSocketController {
}); });
socket.on(SockerIoEvent.DISCONNECT, () => { socket.on(SockerIoEvent.DISCONNECT, () => {
let Client = (socket as ExSocketInterface); const Client = (socket as ExSocketInterface);
try { try {
//leave room //leave room
this.leaveRoom(Client); this.leaveRoom(Client);
@ -245,7 +245,7 @@ export class IoSocketController {
this.sockets.delete(Client.userId); this.sockets.delete(Client.userId);
// Let's log server load when a user leaves // Let's log server load when a user leaves
let srvSockets = this.Io.sockets.sockets; const srvSockets = this.Io.sockets.sockets;
this.nbClientsGauge.dec({ host: os.hostname() }); this.nbClientsGauge.dec({ host: os.hostname() });
console.log('A user left (', Object.keys(srvSockets).length, ' connected users)'); console.log('A user left (', Object.keys(srvSockets).length, ' connected users)');
si.currentLoad().then(data => console.log('Current load: ', data.avgload)); si.currentLoad().then(data => console.log('Current load: ', data.avgload));
@ -255,7 +255,7 @@ export class IoSocketController {
// Let's send the user id to the user // Let's send the user id to the user
socket.on(SockerIoEvent.SET_PLAYER_DETAILS, (playerDetails: SetPlayerDetailsMessage, answerFn) => { socket.on(SockerIoEvent.SET_PLAYER_DETAILS, (playerDetails: SetPlayerDetailsMessage, answerFn) => {
let Client = (socket as ExSocketInterface); const Client = (socket as ExSocketInterface);
Client.name = playerDetails.name; Client.name = playerDetails.name;
Client.character = playerDetails.character; Client.character = playerDetails.character;
answerFn(Client.userId); answerFn(Client.userId);
@ -264,7 +264,7 @@ export class IoSocketController {
} }
searchClientByIdOrFail(userId: string): ExSocketInterface { searchClientByIdOrFail(userId: string): ExSocketInterface {
let client: ExSocketInterface|undefined = this.sockets.get(userId); const client: ExSocketInterface|undefined = this.sockets.get(userId);
if (client === undefined) { if (client === undefined) {
throw new Error("Could not find user with id " + userId); throw new Error("Could not find user with id " + userId);
} }
@ -277,7 +277,7 @@ export class IoSocketController {
Client.to(Client.roomId).emit(SockerIoEvent.USER_LEFT, Client.userId); Client.to(Client.roomId).emit(SockerIoEvent.USER_LEFT, Client.userId);
//user leave previous world //user leave previous world
let world : World|undefined = this.Worlds.get(Client.roomId); const world : World|undefined = this.Worlds.get(Client.roomId);
if(world){ if(world){
world.leave(Client); world.leave(Client);
} }
@ -337,13 +337,13 @@ export class IoSocketController {
if (this.Io.sockets.adapter.rooms[roomId].length < 2 /*|| this.Io.sockets.adapter.rooms[roomId].length >= 4*/) { if (this.Io.sockets.adapter.rooms[roomId].length < 2 /*|| this.Io.sockets.adapter.rooms[roomId].length >= 4*/) {
return; return;
} }
let clients: Array<ExSocketInterface> = (Object.values(this.Io.sockets.sockets) as Array<ExSocketInterface>) const clients: Array<ExSocketInterface> = (Object.values(this.Io.sockets.sockets) as Array<ExSocketInterface>)
.filter((client: ExSocketInterface) => client.webRtcRoomId && client.webRtcRoomId === roomId); .filter((client: ExSocketInterface) => client.webRtcRoomId && client.webRtcRoomId === roomId);
//send start at one client to initialise offer webrtc //send start at one client to initialise offer webrtc
//send all users in room to create PeerConnection in front //send all users in room to create PeerConnection in front
clients.forEach((client: ExSocketInterface, index: number) => { clients.forEach((client: ExSocketInterface, index: number) => {
let clientsId = clients.reduce((tabs: Array<any>, clientId: ExSocketInterface, indexClientId: number) => { const clientsId = clients.reduce((tabs: Array<any>, clientId: ExSocketInterface, indexClientId: number) => {
if (!clientId.userId || clientId.userId === client.userId) { if (!clientId.userId || clientId.userId === client.userId) {
return tabs; return tabs;
} }
@ -395,13 +395,13 @@ export class IoSocketController {
if (Client === undefined) { if (Client === undefined) {
return; return;
}*/ }*/
let Client = this.searchClientByIdOrFail(userId); const Client = this.searchClientByIdOrFail(userId);
this.joinWebRtcRoom(Client, group.getId()); this.joinWebRtcRoom(Client, group.getId());
} }
//disconnect user //disconnect user
disConnectedUser(userId: string, group: Group) { disConnectedUser(userId: string, group: Group) {
let Client = this.searchClientByIdOrFail(userId); const Client = this.searchClientByIdOrFail(userId);
Client.to(group.getId()).emit(SockerIoEvent.WEBRTC_DISCONNECT, { Client.to(group.getId()).emit(SockerIoEvent.WEBRTC_DISCONNECT, {
userId: userId userId: userId
}); });
@ -411,7 +411,7 @@ export class IoSocketController {
// However! In the rare case where the WebRTC connection is not yet established, if we close the connection on one of the player, // However! In the rare case where the WebRTC connection is not yet established, if we close the connection on one of the player,
// the other player will try connecting until a timeout happens (during this time, the connection icon will be displayed for nothing). // the other player will try connecting until a timeout happens (during this time, the connection icon will be displayed for nothing).
// So we also send the disconnect event to the other player. // So we also send the disconnect event to the other player.
for (let user of group.getUsers()) { for (const user of group.getUsers()) {
Client.emit(SockerIoEvent.WEBRTC_DISCONNECT, { Client.emit(SockerIoEvent.WEBRTC_DISCONNECT, {
userId: user.id userId: user.id
}); });

View file

@ -68,7 +68,7 @@ export class Group {
isPartOfGroup(user: UserInterface): boolean isPartOfGroup(user: UserInterface): boolean
{ {
return this.users.indexOf(user) !== -1; return this.users.includes(user);
} }
/*removeFromGroup(users: UserInterface[]): void /*removeFromGroup(users: UserInterface[]): void

View file

@ -62,7 +62,7 @@ export class World {
} }
public leave(user : Identificable){ public leave(user : Identificable){
let userObj = this.users.get(user.userId); const userObj = this.users.get(user.userId);
if (userObj === undefined) { if (userObj === undefined) {
console.warn('User ', user.userId, 'does not belong to world! It should!'); console.warn('User ', user.userId, 'does not belong to world! It should!');
} }
@ -73,7 +73,7 @@ export class World {
} }
public updatePosition(socket : Identificable, userPosition: PointInterface): void { public updatePosition(socket : Identificable, userPosition: PointInterface): void {
let user = this.users.get(socket.userId); const user = this.users.get(socket.userId);
if(typeof user === 'undefined') { if(typeof user === 'undefined') {
return; return;
} }
@ -83,15 +83,15 @@ export class World {
if (typeof user.group === 'undefined') { if (typeof user.group === 'undefined') {
// If the user is not part of a group: // If the user is not part of a group:
// should he join a group? // should he join a group?
let closestItem: UserInterface|Group|null = this.searchClosestAvailableUserOrGroup(user); const closestItem: UserInterface|Group|null = this.searchClosestAvailableUserOrGroup(user);
if (closestItem !== null) { if (closestItem !== null) {
if (closestItem instanceof Group) { if (closestItem instanceof Group) {
// Let's join the group! // Let's join the group!
closestItem.join(user); closestItem.join(user);
} else { } else {
let closestUser : UserInterface = closestItem; const closestUser : UserInterface = closestItem;
let group: Group = new Group([ const group: Group = new Group([
user, user,
closestUser closestUser
], this.connectCallback, this.disconnectCallback); ], this.connectCallback, this.disconnectCallback);
@ -102,7 +102,7 @@ export class World {
} else { } else {
// If the user is part of a group: // If the user is part of a group:
// should he leave the group? // should he leave the group?
let distance = World.computeDistanceBetweenPositions(user.position, user.group.getPosition()); const distance = World.computeDistanceBetweenPositions(user.position, user.group.getPosition());
if (distance > this.groupRadius) { if (distance > this.groupRadius) {
this.leaveGroup(user); this.leaveGroup(user);
} }
@ -120,7 +120,7 @@ export class World {
* @param user * @param user
*/ */
private leaveGroup(user: UserInterface): void { private leaveGroup(user: UserInterface): void {
let group = user.group; const group = user.group;
if (typeof group === 'undefined') { if (typeof group === 'undefined') {
throw new Error("The user is part of no group"); throw new Error("The user is part of no group");
} }
@ -158,7 +158,7 @@ export class World {
return; return;
} }
let distance = World.computeDistance(user, currentUser); // compute distance between peers. const distance = World.computeDistance(user, currentUser); // compute distance between peers.
if(distance <= minimumDistanceFound && distance <= this.minDistance) { if(distance <= minimumDistanceFound && distance <= this.minDistance) {
minimumDistanceFound = distance; minimumDistanceFound = distance;
@ -204,7 +204,7 @@ export class World {
if (group.isFull()) { if (group.isFull()) {
return; return;
} }
let distance = World.computeDistanceBetweenPositions(user.position, group.getPosition()); const distance = World.computeDistanceBetweenPositions(user.position, group.getPosition());
if(distance <= minimumDistanceFound && distance <= this.groupRadius) { if(distance <= minimumDistanceFound && distance <= this.groupRadius) {
minimumDistanceFound = distance; minimumDistanceFound = distance;
matchingItem = group; matchingItem = group;

View file

@ -6,14 +6,14 @@ import { Group } from "../src/Model/Group";
describe("World", () => { describe("World", () => {
it("should connect user1 and user2", () => { it("should connect user1 and user2", () => {
let connectCalledNumber: number = 0; let connectCalledNumber: number = 0;
let connect: ConnectCallback = (user: string, group: Group): void => { const connect: ConnectCallback = (user: string, group: Group): void => {
connectCalledNumber++; connectCalledNumber++;
} }
let disconnect: DisconnectCallback = (user: string, group: Group): void => { const disconnect: DisconnectCallback = (user: string, group: Group): void => {
} }
let world = new World(connect, disconnect, 160, 160, () => {}, () => {}); const world = new World(connect, disconnect, 160, 160, () => {}, () => {});
world.join({ userId: "foo" }, new Point(100, 100)); world.join({ userId: "foo" }, new Point(100, 100));
@ -33,14 +33,14 @@ describe("World", () => {
it("should connect 3 users", () => { it("should connect 3 users", () => {
let connectCalled: boolean = false; let connectCalled: boolean = false;
let connect: ConnectCallback = (user: string, group: Group): void => { const connect: ConnectCallback = (user: string, group: Group): void => {
connectCalled = true; connectCalled = true;
} }
let disconnect: DisconnectCallback = (user: string, group: Group): void => { const disconnect: DisconnectCallback = (user: string, group: Group): void => {
} }
let world = new World(connect, disconnect, 160, 160, () => {}, () => {}); const world = new World(connect, disconnect, 160, 160, () => {}, () => {});
world.join({ userId: "foo" }, new Point(100, 100)); world.join({ userId: "foo" }, new Point(100, 100));
@ -62,14 +62,14 @@ describe("World", () => {
it("should disconnect user1 and user2", () => { it("should disconnect user1 and user2", () => {
let connectCalled: boolean = false; let connectCalled: boolean = false;
let disconnectCallNumber: number = 0; let disconnectCallNumber: number = 0;
let connect: ConnectCallback = (user: string, group: Group): void => { const connect: ConnectCallback = (user: string, group: Group): void => {
connectCalled = true; connectCalled = true;
} }
let disconnect: DisconnectCallback = (user: string, group: Group): void => { const disconnect: DisconnectCallback = (user: string, group: Group): void => {
disconnectCallNumber++; disconnectCallNumber++;
} }
let world = new World(connect, disconnect, 160, 160, () => {}, () => {}); const world = new World(connect, disconnect, 160, 160, () => {}, () => {});
world.join({ userId: "foo" }, new Point(100, 100)); world.join({ userId: "foo" }, new Point(100, 100));