강동현

MessageHandlerRegistry 구현

import { Socket } from "socket.io";
import { MessageHandlerRegister } from "../message/handler/MessageHandlerRegister";
import { MessageHandlerRegistry } from "../message/MessageHandlerRegistry";
import { User } from "../user/User";
export class Connection {
......@@ -10,7 +10,7 @@ export class Connection {
constructor(socket: Socket) {
this.socket = socket;
MessageHandlerRegister.registerMessageHandlers(this);
MessageHandlerRegistry.registerHandlers(this);
}
public get authenticated(): boolean {
......
import { Connection } from "../connection/Connection";
import { loginHandler } from "./handler/LoginHandler";
import { MessageType } from "./types";
export class MessageHandlerRegistry {
static registerHandlers(connection: Connection) {
this.registerHandler(connection, MessageType.LOGIN, loginHandler);
}
private static registerHandler<T>(
connection: Connection,
typeName: string,
handler: (connection: Connection, message: T) => void
) {
connection.socket.on(typeName, (message: T) => {
handler(connection, message);
});
}
}
import { Connection } from "../../connection/Connection";
import { User } from "../../user/User";
import { LoginMessage } from "../types";
import { MessageHandler } from "./MessageHandler";
export class LoginHandler implements MessageHandler<LoginMessage> {
public handle(connection: Connection, message: LoginMessage): void {
connection.user = new User(message.username);
console.log(`User ${message.username} has logged in!`);
}
export function loginHandler(
connection: Connection,
message: LoginMessage
): void {
connection.user = new User(message.username);
console.log(`User ${message.username} has logged in!`);
}
......
import { Connection } from "../../connection/Connection";
export interface MessageHandler<T> {
handle(connection: Connection, message: T): void;
}
import { Connection } from "../../connection/Connection";
import { LoginMessage } from "../types";
import { LoginHandler } from "./LoginHandler";
export class MessageHandlerRegister {
static registerMessageHandlers(connection: Connection) {
connection.socket.on("login", (message: LoginMessage) => {
new LoginHandler().handle(connection, message);
});
}
}
export interface LoginMessage {
username: string;
}
export class MessageType {
static readonly LOGIN = "login";
}
......