This repository has been archived on 2021-06-02. You can view files and clone it, but cannot push or open issues or pull requests.
RealtimeDB-OLD/src/connection.ts

67 lines
2.2 KiB
TypeScript
Raw Normal View History

2019-09-18 19:54:28 +00:00
import * as io from "socket.io";
import { Server } from "http";
import { DatabaseManager } from "./database/database";
import Logging from "@hibas123/logging";
type QueryTypes = "get" | "set" | "push" | "subscribe" | "unsubscribe";
export class ConnectionManager {
static server: io.Server;
static bind(server: Server) {
this.server = io(server);
this.server.on("connection", this.onConnection.bind(this));
}
private static onConnection(socket: io.Socket) {
const reqMap = new Map<string, [number, number]>();
const answer = (id: string, data: any, err: boolean = false) => {
let time = process.hrtime(reqMap.get(id));
Logging.debug(`Sending answer for ${id} with data`, data, err ? "as error" : "", "Took", time[1] / 1000, "us");
socket.emit("message", id, err, data);
}
socket.on("login", (id: string) => {
//TODO: implement
})
socket.on("query", async (id: string, type: QueryTypes, database: string, path: string[], data: any) => {
Logging.debug(`Request with id ${id} from type ${type} for database ${database} and path ${path} with data ${data}`)
reqMap.set(id, process.hrtime());
try {
const db = DatabaseManager.getDatabase(database);
if (!db)
answer(id, "Database not found!", true);
else {
const query = db.getQuery(path);
switch (type) {
case "get":
answer(id, await query.get());
break;
case "set":
answer(id, await query.set(data));
break;
case "push":
answer(id, await query.push(data));
break;
case "subscribe":
answer(id, await query.subscribe());
break;
case "unsubscribe":
answer(id, await query.unsubscribe());
break;
}
}
} catch (err) {
Logging.error(err);
answer(id, err.message, true);
}
})
socket.on("disconnect", () => {
})
}
}