Andrea D'Attero
Andrea D'Attero

Reputation: 65

Improving Socket.io code with Typescript Decorators

I am trying to simplify the logic of socket.io by using decorators as follows:

const Event: any = (name) => {
    return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
        console.log(target, propertyKey, descriptor);
    };
};

class ServerRoom {
    private server: Server;

    @Event("connection")
    onConnection(socket: Socket) {

    }

}

class PlayerRoom {
    private socket: Socket;

    constructor(socket: Socket) {
        this.socket = socket;
    }

    @Event("move")
    onMove(move: any) {
        console.log("Move: ", move);
    }

    @Event("disconnect")
    onDisconnect() {
        console.log("disconnected");
    }

}

What I would like is to call onMove when the socket in PlayerRoom received the event "move" same also for "disconnect" and "connect", how should I go for this?

Upvotes: 0

Views: 187

Answers (1)

Benoît Lahoz
Benoît Lahoz

Reputation: 1366

There are some implementations in existing packages that could be inspiring or you could use:

In you’re implementation you have to pass everything necessary for your decorator to work: e.g. here you’re not passing any reference to the room, or I have been misreading.

PlayerRoom class is aware of the socket instance, but not of the room’s id and connection state. These could be provided by a Class decorator with socket + eventual namespace + room as parameters, for example.

Upvotes: 0

Related Questions