forked from noxious/server
Added socketManager and moved logic into it where appropiate
This commit is contained in:
69
src/managers/socketManager.ts
Normal file
69
src/managers/socketManager.ts
Normal file
@ -0,0 +1,69 @@
|
||||
import fs from 'fs'
|
||||
import { pathToFileURL } from 'url'
|
||||
|
||||
import { Server as SocketServer } from 'socket.io'
|
||||
|
||||
import Logger, { LoggerType } from '#application/logger'
|
||||
import { getAppPath } from '#application/storage'
|
||||
import { TSocket } from '#application/types'
|
||||
|
||||
class SocketManager {
|
||||
private io: any
|
||||
private logger = Logger.type(LoggerType.APP)
|
||||
|
||||
public async boot(io: SocketServer) {
|
||||
this.io = io
|
||||
io.on('connection', this.handleConnection.bind(this))
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle socket connection
|
||||
* @param socket
|
||||
* @private
|
||||
*/
|
||||
private async handleConnection(socket: TSocket) {
|
||||
try {
|
||||
await this.loadEventHandlers('events', '', socket)
|
||||
} catch (error: any) {
|
||||
this.logger.error(`Failed to load event handlers: ${error.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
private async loadEventHandlers(baseDir: string, subDir: string, socket: TSocket) {
|
||||
try {
|
||||
const fullDir = getAppPath(baseDir, subDir)
|
||||
const files = await fs.promises.readdir(fullDir, { withFileTypes: true })
|
||||
|
||||
for (const file of files) {
|
||||
const filePath = getAppPath(baseDir, subDir, file.name)
|
||||
|
||||
if (file.isDirectory()) {
|
||||
await this.loadEventHandlers(baseDir, `${subDir}/${file.name}`, socket)
|
||||
continue
|
||||
}
|
||||
|
||||
if (!file.isFile() || (!file.name.endsWith('.ts') && !file.name.endsWith('.js'))) {
|
||||
continue
|
||||
}
|
||||
|
||||
try {
|
||||
const module = await import(pathToFileURL(filePath).href)
|
||||
if (typeof module.default !== 'function') {
|
||||
this.logger.warn(`Unrecognized export in ${file.name}`)
|
||||
continue
|
||||
}
|
||||
|
||||
const EventClass = module.default
|
||||
const eventInstance = new EventClass(this.io, socket)
|
||||
eventInstance.listen()
|
||||
} catch (error) {
|
||||
this.logger.error(`Error loading event handler ${file.name}: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error(`Error reading directory: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default new SocketManager()
|
Reference in New Issue
Block a user