diff --git a/src/api/ApiManager.ts b/src/api/ApiManager.ts index 7c753d7..86517bd 100644 --- a/src/api/ApiManager.ts +++ b/src/api/ApiManager.ts @@ -1,14 +1,15 @@ -import BaseApi from './BaseApi.ts' import HttpServerLike from '../types/HttpServerLike.ts' import UserApi from "./UserApi.ts" import SocketIo from "socket.io" -import UnknownFunction from "../types/UnknownFunction.ts"; +import ApiCallbackMessage from "../types/ApiCallbackMessage.ts" +import EventCallbackFunction from "../types/EventCallbackFunction.ts" export default class ApiManager { static httpServer: HttpServerLike static socketIoServer: SocketIo.Server + static event_listeners: { [key: string] : EventCallbackFunction } = {} static apis_instance: {} - static init(httpServer: HttpServerLike, socketIoServer: SocketIo.Server) { + static initServer(httpServer: HttpServerLike, socketIoServer: SocketIo.Server) { this.httpServer = httpServer this.socketIoServer = socketIoServer } @@ -23,13 +24,19 @@ export default class ApiManager { user: new UserApi() } } + static addEventListener(name: string, func: EventCallbackFunction) { + this.event_listeners[name] = func + } static initEvents() { const io = this.socketIoServer io.on('connection', (socket) => { - socket.on("The_White_Silk", (name: string, args: {}, callback: UnknownFunction) => { + socket.on("The_White_Silk", (name: string, args: {}, callback: (ret: ApiCallbackMessage) => void) => { if (name == null || args == null) return callback({ - + msg: "Invalid request.", + code: 400 }) + + return callback(this.event_listeners[name]?.(args)) }) }) } diff --git a/src/api/BaseApi.ts b/src/api/BaseApi.ts index 2d83ca8..ea12464 100644 --- a/src/api/BaseApi.ts +++ b/src/api/BaseApi.ts @@ -1,4 +1,4 @@ -import UnknownFunction from '../types/UnknownFunction.ts' +import EventCallbackFunction from "../types/EventCallbackFunction.ts" import ApiManager from "./ApiManager.ts"; export default abstract class BaseApi { @@ -7,8 +7,7 @@ export default abstract class BaseApi { this.onInit() } abstract onInit(): void - registerEvent(name: string, func: UnknownFunction) { - const io = ApiManager.getSocketIoServer() - + registerEvent(name: string, func: EventCallbackFunction) { + ApiManager.addEventListener(this.getName() + "." + name, func) } } diff --git a/src/types/EventCallbackFunction.ts b/src/types/EventCallbackFunction.ts new file mode 100644 index 0000000..237920b --- /dev/null +++ b/src/types/EventCallbackFunction.ts @@ -0,0 +1,5 @@ +import ApiCallbackMessage from "./ApiCallbackMessage.ts" + +type EventCallbackFunction = (args: {}) => ApiCallbackMessage + +export default EventCallbackFunction