-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSetup.js
More file actions
84 lines (76 loc) · 2.57 KB
/
Setup.js
File metadata and controls
84 lines (76 loc) · 2.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import fs from 'fs'
import path from 'path'
import BaseController from './server/utils/BaseController'
import { logger } from './server/utils/Logger'
export class Paths {
static get Public() {
return path.join(__dirname, 'client')
}
static get Server() {
return path.join(__dirname, 'server')
}
static get Controllers() {
return this.Server + '/controllers'
}
static get Handlers() {
return this.Server + '/handlers'
}
}
export function RegisterControllers(router) {
const controllers = fs.readdirSync(Paths.Controllers)
controllers.forEach(loadController)
async function loadController(controllerName) {
try {
if (!controllerName.endsWith('.js')) return
const fileHandler = await import(Paths.Controllers + '/' + controllerName)
let ControllerClass = fileHandler[controllerName.slice(0, -3)]
if (!ControllerClass) {
throw new Error(`${controllerName} The exported class does not match the filename`)
}
if (ControllerClass.default) {
ControllerClass = ControllerClass.default
}
const controller = new ControllerClass()
if (controller instanceof BaseController) {
router.use(controller.mount, controller.router)
}
} catch (e) {
logger.error(
'[CONTROLLER ERROR] unable to load controller, potential duplication, review mount path and controller class name, and see error below',
controllerName,
e
)
}
}
}
const HANDLERS = []
export async function RegisterSocketHandlers() {
const directory = Paths.Handlers
const handlers = fs.readdirSync(directory)
handlers.forEach(async(handlerName) => {
try {
if (!handlerName.endsWith('.js')) { return }
const fileHandler = await import(directory + '/' + handlerName)
let HandlerClass = fileHandler[handlerName.slice(0, -3)]
if (!HandlerClass) {
throw new Error(`${handlerName} The exported class does not match the filename`)
}
if (HandlerClass.default) {
HandlerClass = HandlerClass.default
}
HANDLERS.push(HandlerClass)
} catch (e) {
logger.error(
'[SOCKET_HANDLER_ERROR] unable to attach socket handler, potential duplication, review mount path and controller class name, and see error below',
handlerName,
e
)
}
})
}
export async function attachHandlers(io, socket, user, profile) {
if (socket._handlers && user && profile) {
return socket._handlers.forEach(handler => handler.attachUser(user, profile))
}
socket._handlers = HANDLERS.map(Handler => new Handler(io, socket))
}