Refactoring messages

Socket.io can stringify JSON messages itself, so there is no need to pass a string to "emit". You can pass a serializable object!

This commit removes all the useless toJson() methods, JSON.serialize and JSON.parse!

Woot!
This commit is contained in:
David Négrier 2020-05-15 22:04:49 +02:00
parent 2411a3f85a
commit 5a3668a12e
3 changed files with 25 additions and 55 deletions

View File

@ -97,7 +97,7 @@ export class IoSocketController {
try { try {
let messageUserPosition = this.hydrateMessageReceive(message); let messageUserPosition = this.hydrateMessageReceive(message);
if (messageUserPosition instanceof Error) { if (messageUserPosition instanceof Error) {
return socket.emit(SockerIoEvent.MESSAGE_ERROR, JSON.stringify({message: messageUserPosition.message})) return socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: messageUserPosition.message})
} }
let Client = (socket as ExSocketInterface); let Client = (socket as ExSocketInterface);
@ -129,7 +129,7 @@ export class IoSocketController {
try { try {
let messageUserPosition = this.hydrateMessageReceive(message); let messageUserPosition = this.hydrateMessageReceive(message);
if (messageUserPosition instanceof Error) { if (messageUserPosition instanceof Error) {
return socket.emit(SockerIoEvent.MESSAGE_ERROR, JSON.stringify({message: messageUserPosition.message})); return socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: messageUserPosition.message});
} }
let Client = (socket as ExSocketInterface); let Client = (socket as ExSocketInterface);
@ -145,19 +145,17 @@ export class IoSocketController {
} }
}); });
socket.on(SockerIoEvent.WEBRTC_SIGNAL, (message: string) => { socket.on(SockerIoEvent.WEBRTC_SIGNAL, (data: any) => {
let data: any = JSON.parse(message);
//send only at user //send only at user
let client = this.searchClientById(data.receiverId); let client = this.searchClientById(data.receiverId);
if (!client) { if (!client) {
console.error("client doesn't exist for ", data.receiverId); console.error("client doesn't exist for ", data.receiverId);
return; return;
} }
return client.emit(SockerIoEvent.WEBRTC_SIGNAL, message); return client.emit(SockerIoEvent.WEBRTC_SIGNAL, data);
}); });
socket.on(SockerIoEvent.WEBRTC_OFFER, (message: string) => { socket.on(SockerIoEvent.WEBRTC_OFFER, (data: any) => {
let data: any = JSON.parse(message);
//send only at user //send only at user
let client = this.searchClientById(data.receiverId); let client = this.searchClientById(data.receiverId);
@ -165,7 +163,7 @@ export class IoSocketController {
console.error("client doesn't exist for ", data.receiverId); console.error("client doesn't exist for ", data.receiverId);
return; return;
} }
client.emit(SockerIoEvent.WEBRTC_OFFER, message); client.emit(SockerIoEvent.WEBRTC_OFFER, data);
}); });
socket.on(SockerIoEvent.DISCONNECT, () => { socket.on(SockerIoEvent.DISCONNECT, () => {
@ -212,6 +210,7 @@ export class IoSocketController {
return client; return client;
} }
console.log("Could not find user with id ", userId); console.log("Could not find user with id ", userId);
throw new Error("Could not find user with id " + userId);
return null; return null;
} }
@ -235,9 +234,9 @@ export class IoSocketController {
* @param Client: ExSocketInterface * @param Client: ExSocketInterface
*/ */
sendDisconnectedEvent(Client: ExSocketInterface) { sendDisconnectedEvent(Client: ExSocketInterface) {
Client.broadcast.emit(SockerIoEvent.WEBRTC_DISCONNECT, JSON.stringify({ Client.broadcast.emit(SockerIoEvent.WEBRTC_DISCONNECT, {
userId: Client.id userId: Client.id
})); });
//disconnect webrtc room //disconnect webrtc room
if(!Client.webRtcRoomId){ if(!Client.webRtcRoomId){
@ -257,7 +256,6 @@ export class IoSocketController {
//user leave previous world //user leave previous world
let world : World|undefined = this.Worlds.get(Client.roomId); let world : World|undefined = this.Worlds.get(Client.roomId);
if(world){ if(world){
console.log('Entering world.leave')
world.leave(Client); world.leave(Client);
//this.Worlds.set(Client.roomId, world); //this.Worlds.set(Client.roomId, world);
} }
@ -341,7 +339,7 @@ export class IoSocketController {
return tabs; return tabs;
}, []); }, []);
client.emit(SockerIoEvent.WEBRTC_START, JSON.stringify({clients: clientsId, roomId: roomId})); client.emit(SockerIoEvent.WEBRTC_START, {clients: clientsId, roomId: roomId});
}); });
} }
@ -382,7 +380,7 @@ export class IoSocketController {
//Hydrate and manage error //Hydrate and manage error
hydrateMessageReceive(message: string): MessageUserPosition | Error { hydrateMessageReceive(message: string): MessageUserPosition | Error {
try { try {
return new MessageUserPosition(JSON.parse(message)); return new MessageUserPosition(message);
} catch (err) { } catch (err) {
//TODO log error //TODO log error
return new Error(err); return new Error(err);
@ -421,7 +419,7 @@ export class IoSocketController {
} }
arrayMap.forEach((value: any) => { arrayMap.forEach((value: any) => {
let roomId = value[0]; let roomId = value[0];
this.Io.in(roomId).emit(SockerIoEvent.USER_POSITION, JSON.stringify(value)); this.Io.in(roomId).emit(SockerIoEvent.USER_POSITION, value);
}); });
this.seTimeOutInProgress = setTimeout(() => { this.seTimeOutInProgress = setTimeout(() => {
this.shareUsersPosition(); this.shareUsersPosition();

View File

@ -34,22 +34,12 @@ class Message {
this.name = name; this.name = name;
this.character = character; this.character = character;
} }
toJson() {
return {
userId: this.userId,
roomId: this.roomId,
name: this.name,
character: this.character
}
}
} }
export interface PointInterface { export interface PointInterface {
x: number; x: number;
y: number; y: number;
direction : string; direction : string;
toJson() : object;
} }
class Point implements PointInterface{ class Point implements PointInterface{
@ -65,14 +55,6 @@ class Point implements PointInterface{
this.y = y; this.y = y;
this.direction = direction; this.direction = direction;
} }
toJson(){
return {
x : this.x,
y: this.y,
direction: this.direction
}
}
} }
export interface MessageUserPositionInterface { export interface MessageUserPositionInterface {
@ -90,16 +72,6 @@ class MessageUserPosition extends Message implements MessageUserPositionInterfac
super(userId, roomId, name, character); super(userId, roomId, name, character);
this.position = point; this.position = point;
} }
toString() {
return JSON.stringify(
Object.assign(
super.toJson(),
{
position: this.position.toJson()
})
);
}
} }
export interface ListMessageUserPositionInterface { export interface ListMessageUserPositionInterface {
@ -274,7 +246,7 @@ export class Connexion implements ConnexionInterface {
this.email, this.email,
character character
); );
this.socket.emit(EventMessage.JOIN_ROOM, messageUserPosition.toString()); this.socket.emit(EventMessage.JOIN_ROOM, messageUserPosition);
} }
/** /**
@ -297,7 +269,7 @@ export class Connexion implements ConnexionInterface {
character character
); );
this.lastPositionShared = messageUserPosition; this.lastPositionShared = messageUserPosition;
this.socket.emit(EventMessage.USER_POSITION, messageUserPosition.toString()); this.socket.emit(EventMessage.USER_POSITION, messageUserPosition);
} }
attributeUserId(): void { attributeUserId(): void {
@ -326,7 +298,7 @@ export class Connexion implements ConnexionInterface {
**/ **/
positionOfAllUser(): void { positionOfAllUser(): void {
this.socket.on(EventMessage.USER_POSITION, (message: string) => { this.socket.on(EventMessage.USER_POSITION, (message: string) => {
let dataList = JSON.parse(message); let dataList = message;
let UserPositions : Array<any> = Object.values(dataList); let UserPositions : Array<any> = Object.values(dataList);
let listMessageUserPosition = new ListMessageUserPosition(UserPositions[0], UserPositions[1]); let listMessageUserPosition = new ListMessageUserPosition(UserPositions[0], UserPositions[1]);
this.GameManager.shareUserPosition(listMessageUserPosition); this.GameManager.shareUserPosition(listMessageUserPosition);
@ -347,12 +319,12 @@ export class Connexion implements ConnexionInterface {
} }
sendWebrtcSignal(signal: any, roomId: string, userId? : string, receiverId? : string) { sendWebrtcSignal(signal: any, roomId: string, userId? : string, receiverId? : string) {
return this.socket.emit(EventMessage.WEBRTC_SIGNAL, JSON.stringify({ return this.socket.emit(EventMessage.WEBRTC_SIGNAL, {
userId: userId ? userId : this.userId, userId: userId ? userId : this.userId,
receiverId: receiverId ? receiverId : this.userId, receiverId: receiverId ? receiverId : this.userId,
roomId: roomId, roomId: roomId,
signal: signal signal: signal
})); });
} }
receiveWebrtcStart(callback: Function) { receiveWebrtcStart(callback: Function) {

View File

@ -32,7 +32,7 @@ export class SimplePeer implements SimplePeerInterface{
private initialise() { private initialise() {
//receive signal by gemer //receive signal by gemer
this.Connexion.receiveWebrtcSignal((message: string) => { this.Connexion.receiveWebrtcSignal((message: any) => {
this.receiveWebrtcSignal(message); this.receiveWebrtcSignal(message);
}); });
@ -40,7 +40,7 @@ export class SimplePeer implements SimplePeerInterface{
this.MediaManager.getCamera().then(() => { this.MediaManager.getCamera().then(() => {
//receive message start //receive message start
this.Connexion.receiveWebrtcStart((message: string) => { this.Connexion.receiveWebrtcStart((message: any) => {
this.receiveWebrtcStart(message); this.receiveWebrtcStart(message);
}); });
@ -49,8 +49,8 @@ export class SimplePeer implements SimplePeerInterface{
}); });
//receive signal by gemer //receive signal by gemer
this.Connexion.disconnectMessage((message: string) => { this.Connexion.disconnectMessage((message: any) => {
let data = JSON.parse(message); let data = message;
this.closeConnexion(data.userId); this.closeConnexion(data.userId);
}); });
} }
@ -59,8 +59,8 @@ export class SimplePeer implements SimplePeerInterface{
* *
* @param message * @param message
*/ */
private receiveWebrtcStart(message: string) { private receiveWebrtcStart(message: any) {
let data = JSON.parse(message); let data = message;
this.WebRtcRoomId = data.roomId; this.WebRtcRoomId = data.roomId;
this.Users = data.clients; this.Users = data.clients;
@ -197,8 +197,8 @@ export class SimplePeer implements SimplePeerInterface{
* *
* @param message * @param message
*/ */
private receiveWebrtcSignal(message: string) { private receiveWebrtcSignal(message: any) {
let data = JSON.parse(message); let data = message;
try { try {
//if offer type, create peer connexion //if offer type, create peer connexion
if(data.signal.type === "offer"){ if(data.signal.type === "offer"){