Created
April 8, 2021 18:33
-
-
Save drasch/49264fff053f924e16dbe81f444f96da to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { log, Config, ConfigImpl, EnvSetup, EventBus, Message } from "./services/config"; | |
import { Server, Socket } from "socket.io"; | |
import http from "http"; | |
import handler from "serve-handler"; | |
import devices from "./services/device"; | |
import path from "path"; | |
import serialize from "serialize-javascript"; | |
export class SocketMessage implements Message { | |
constructor(public server: Server) {} | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
reply(name: string, ...args: any[]) { | |
log.info("EMMITTING EVENT", name, args); | |
this.server.emit(name, ...args.map(serialize)); | |
} | |
} | |
export class SocketEventBus implements EventBus { | |
io: Server; | |
sockets: Record<number, Socket> = {}; | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
listeners: Record<string, (event: Message, ...args: any[]) => void> = {}; | |
constructor() { | |
const staticsPath = path.join(path.dirname(__dirname), "frontend"); | |
const server = http.createServer((req, res) => handler(req, res, { public: staticsPath })); | |
server.listen(3000); | |
this.io = new Server(server); | |
this.io.on("connection", socket => { | |
for (const [name, callback] of Object.entries(this.listeners)) { | |
socket.on(name, callback); | |
} | |
this.sockets[socket.id] = socket; | |
log.info("user connected"); | |
socket.on("disconnect", () => { | |
delete this.sockets[socket.id]; | |
log.info("user disconnected"); | |
}); | |
}); | |
this.io.sockets.setMaxListeners(15); | |
} | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
on(name: string, callback: (event: Message, ...args: any[]) => void) { | |
log.info("message: ", name); | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
this.listeners[name] = (...args: any[]) => { | |
callback(new SocketMessage(this.io), ...args); | |
}; | |
} | |
} | |
export class NodeConfig extends Config implements ConfigImpl { | |
eventBus: EventBus; | |
constructor() { | |
super(); | |
EnvSetup.prod(); | |
if (process.env.NODE_ENV != "development") { | |
process.env.NIKA_BACKUP_PATH = "/var/lib/nika/backups"; | |
} | |
process.env.KEYPATH = path.join(__dirname, "outpost-development-upload.json"); | |
this.eventBus = new SocketEventBus(); | |
console.log("starting node!"); | |
console.log("starting node!"); | |
devices.register(this); | |
console.log("still node!"); | |
} | |
} | |
const config = new NodeConfig(); | |
log.info(config); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment