From 9c5410c77655f76b7ecb002d1ccbeda66f53b7cd Mon Sep 17 00:00:00 2001 From: Dark Waves Tech <89140466+darkwaves-ofc@users.noreply.github.com> Date: Tue, 2 Jan 2024 21:39:48 +0530 Subject: [PATCH] fixed some. --- package.json | 2 +- src/handlers/initDatabase.ts | 32 +++++++++++- src/handlers/loadincomingEvents.ts | 27 +++------- src/handlers/loadroutes.ts | 15 +++--- src/handlers/sendSystemStatus.ts | 6 +-- src/handlers/types.ts | 15 ------ src/index.ts | 28 +++++----- src/structures/App.ts | 9 ++-- src/utils/filterData.ts | 82 +++++++++++++++--------------- src/utils/getSystemSpecs.ts | 17 ++++++- src/utils/logger.ts | 2 +- src/websocket/v1/home.ts | 8 ++- src/websocket/v1/public.ts | 8 ++- 13 files changed, 139 insertions(+), 112 deletions(-) delete mode 100644 src/handlers/types.ts diff --git a/package.json b/package.json index bafb870..ba56cfe 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "nodejs-backend-structure", - "version": "1.1.1", + "version": "1.1.2", "description": "NodeJS Backend Structure.", "main": "dist/index.js", "preview": false, diff --git a/src/handlers/initDatabase.ts b/src/handlers/initDatabase.ts index af10588..3166335 100644 --- a/src/handlers/initDatabase.ts +++ b/src/handlers/initDatabase.ts @@ -4,11 +4,39 @@ import { EventEmitter } from "events"; import { readdir } from "fs"; import dashboardDataDb from "../schema/dashboard"; import userData from "../schema/userData"; +import { AppTypes } from "../structures/App"; + +// interface Schema { +// _id: { +// $oid: string; +// }; +// type: string; +// navigationLinks: ({ +// title: string; +// icon: string; +// path: string; +// url: string; +// _id: { +// $oid: string; +// }; +// subMenu: never[]; +// } | { +// title: string; +// icon: string; +// path: string; +// url: string; +// _id: { +// $oid: string; +// }; +// subMenu?: undefined; +// })[]; +// __v: number; +// } export = class DatabaseInitializer { - private client: any; + private client: AppTypes; - constructor(client: any) { + constructor(client: AppTypes) { if (!client) throw new Error(`client is required`); this.client = client; } diff --git a/src/handlers/loadincomingEvents.ts b/src/handlers/loadincomingEvents.ts index fe22ffe..8530937 100644 --- a/src/handlers/loadincomingEvents.ts +++ b/src/handlers/loadincomingEvents.ts @@ -2,33 +2,20 @@ import { EventEmitter } from "events"; import { readdir } from "fs"; -import socketIo, { Server, Socket } from "socket.io"; -import { ParsedUrlQuery } from "querystring"; - -interface Client { - server: any; - config: any; - links: string[]; - parseURL: (link: string) => any; - ipport: (link: string, port: number) => string; - port: number; - logger: any; - wspaths: Map; - io: Server; - wsevents: EventEmitter; -} +import socketIo, { Socket } from "socket.io"; +import { AppTypes } from "../structures/App"; interface WebSocketPath { default: { name: string; - run: (client: Client, socket: Socket, request: any) => void; + run: (client: AppTypes, socket: Socket, request: Socket) => void; }; } export = class WebSocketInitializer { - private client: Client; + private client: AppTypes; - constructor(client: Client) { + constructor(client: AppTypes) { if (!client) throw new Error(`client is required`); this.client = client; this.client.wspaths = new Map(); @@ -49,7 +36,7 @@ export = class WebSocketInitializer { }); this.client.io = io; - io.use((socket: any, next: any) => { + io.use((socket, next) => { const { host } = socket.request.headers; let checkHost = false; @@ -110,7 +97,7 @@ export = class WebSocketInitializer { for (const [name, path] of this.client.wspaths) { const nameSpace = io.of(name); - nameSpace.on("connection", (socket: any) => { + nameSpace.on("connection", (socket: Socket) => { path.run(this.client, socket, socket.request); }); } diff --git a/src/handlers/loadroutes.ts b/src/handlers/loadroutes.ts index 3d95cd9..c0ce154 100644 --- a/src/handlers/loadroutes.ts +++ b/src/handlers/loadroutes.ts @@ -1,11 +1,7 @@ "use strict"; import { readdir } from "fs"; - -interface Client { - routes: Map; - logger: any; -} +import { AppTypes } from "../structures/App"; interface Route { version: string; @@ -13,13 +9,16 @@ interface Route { interface Path { name: string; - route: any; // Replace 'any' with an appropriate type based on your route structure + route: RouteConstructor; +} +interface RouteConstructor { + new (client: AppTypes): Route; // If Route is a class and takes AppTypes in its constructor } export = class RoutesInitializer { - private client: Client; + private client: AppTypes; - constructor(client: Client) { + constructor(client: AppTypes) { if (!client) throw new Error(`client is required`); this.client = client; } diff --git a/src/handlers/sendSystemStatus.ts b/src/handlers/sendSystemStatus.ts index 88623c2..1295a81 100644 --- a/src/handlers/sendSystemStatus.ts +++ b/src/handlers/sendSystemStatus.ts @@ -2,12 +2,12 @@ import updateSystemSpecs from "../utils/getSystemSpecs"; import { readdir } from "fs"; -import { Client } from "./types"; // Replace './types' with the path to your types file +import { AppTypes } from "../structures/App"; export = class SystemInformation { - private client: Client; + private client: AppTypes; - constructor(client: Client) { + constructor(client: AppTypes) { if (!client) throw new Error(`client is required`); this.client = client; } diff --git a/src/handlers/types.ts b/src/handlers/types.ts deleted file mode 100644 index ba74f99..0000000 --- a/src/handlers/types.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { Server } from "socket.io"; -import { EventEmitter } from "events"; - -export interface Client { - server: any; - config: any; - links: string[]; - parseURL: (link: string) => any; - ipport: (link: string, port: number) => string; - port: number; - logger: any; - wspaths: Map; - io: Server; - wsevents: EventEmitter; -} diff --git a/src/index.ts b/src/index.ts index bed2507..d77e8b1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,7 +7,7 @@ import readline from "readline"; const client = new App(); -process.on("unhandledRejection", (reason: any, p: any) => { +process.on("unhandledRejection", (reason, p) => { console.log("\n\n\n\n\n=== unhandled Rejection ===".toUpperCase().yellow.dim); console.log(reason); console.log("=== unhandled Rejection ===\n\n\n\n\n".toUpperCase().yellow.dim); @@ -37,25 +37,23 @@ process.on("exit", (code: number) => { console.log("=== exit ===\n\n\n\n\n".toUpperCase().yellow.dim); }); -process.on( - "multipleResolves", - (type: string, promise: Promise, reason: any) => { - // Do something for multipleResolves event - } -); +process.on("multipleResolves", (type, promise, reason) => { + // Do something for multipleResolves event +}); function getIPv4Addresses(): string | undefined { const networkInterfaces = os.networkInterfaces(); let ipv4Address: string | undefined; Object.keys(networkInterfaces).forEach((interfaceName) => { - const interfaceInfo: any = networkInterfaces[interfaceName]; - - interfaceInfo.forEach((info: any) => { - if (info.family === "IPv4" && info.internal === false) { - ipv4Address = info.address; - } - }); + const interfaceInfo = networkInterfaces[interfaceName]; + if (interfaceInfo) { + interfaceInfo.forEach((info) => { + if (info.family === "IPv4" && info.internal === false) { + ipv4Address = info.address; + } + }); + } }); return ipv4Address; @@ -103,7 +101,7 @@ new Promise((resolve) => { } } - const allips = client.config.website.links.map((val: any) => { + const allips = client.config.website.links.map((val) => { return (val = `${val}:${client.config.website.port}`); }); diff --git a/src/structures/App.ts b/src/structures/App.ts index 51ff802..8cbd0c3 100644 --- a/src/structures/App.ts +++ b/src/structures/App.ts @@ -8,6 +8,8 @@ import jwt from "jsonwebtoken"; import userDataDb from "../schema/userData"; import cors from "cors"; import { LoggerType, logger } from "../utils/logger"; +import EventEmitter from "events"; +import socketIo, { Server as SocketServer, Socket } from "socket.io"; import { Server } from "http"; // import * as CircularJSON from "circular-json"; // import * as dayjs from "dayjs"; @@ -49,10 +51,11 @@ interface App { findUser: FindUserFunction; connect: () => Promise; app: express.Express; + wspaths: Map; + io: SocketServer; + wsevents: EventEmitter; } -export interface AppTypes extends App { - -} +export interface AppTypes extends App {} class App { constructor() { this.config = config; diff --git a/src/utils/filterData.ts b/src/utils/filterData.ts index 6580851..ca5b0cd 100644 --- a/src/utils/filterData.ts +++ b/src/utils/filterData.ts @@ -1,4 +1,5 @@ import dayjs from "dayjs"; +import { AppTypes } from "../structures/App"; interface UserData { profilePicture: string; @@ -17,55 +18,56 @@ interface UserData { }; } +interface DestrucuredData { + profilePicture: string; + bio: string; + userName: string; + id: string; + name: string; + school: string; + owner: boolean; + createdAt: dayjs.Dayjs; // Update to correct type Dayjs + role: string; + editAccessRoles?: { + roleIndex: number; + roleType: string; + }[]; +} + class FilterData { - private client: any; + private client: AppTypes; - constructor(client: any) { + constructor(client: AppTypes) { this.client = client; } - async user(userType: string, findingUserData: UserData) { - const destrucuredData: any = {}; + user(userType: string, findingUserData: UserData): DestrucuredData { + const destrucuredData: DestrucuredData = { + profilePicture: findingUserData.profilePicture || "", + bio: findingUserData.bio || "", + userName: findingUserData.userName || "", + id: String(findingUserData._id) || "", + name: findingUserData.name || "", + school: findingUserData.school || "", + owner: findingUserData.owner || false, + createdAt: dayjs(findingUserData.createdAt), // Initialize with dayjs + role: findingUserData.roles.roleType || "", + }; - switch (userType === "@me") { - case true: { - this.populateDestructuredData(destrucuredData, findingUserData); - - if (findingUserData.roles.roleIndex === "1") { - destrucuredData.editAcessRoles = [ - { roleIndex: 2, roleType: "admin" }, - { roleIndex: 3, roleType: "staff" }, - ]; - } else if (findingUserData.roles.roleIndex === "2") { - destrucuredData.editAcessRoles = [ - { roleIndex: 3, roleType: "staff" }, - ]; - } else if (findingUserData.roles.roleIndex === "3") { - destrucuredData.editAcessRoles = []; - } - break; - } - case false: { - this.populateDestructuredData(destrucuredData, findingUserData); - break; + if (userType === "@me") { + if (findingUserData.roles.roleIndex === "1") { + destrucuredData.editAccessRoles = [ + { roleIndex: 2, roleType: "admin" }, + { roleIndex: 3, roleType: "staff" }, + ]; + } else if (findingUserData.roles.roleIndex === "2") { + destrucuredData.editAccessRoles = [{ roleIndex: 3, roleType: "staff" }]; + } else if (findingUserData.roles.roleIndex === "3") { + destrucuredData.editAccessRoles = []; } } - return destrucuredData; - } - private populateDestructuredData( - destrucuredData: any, - findingUserData: UserData - ) { - destrucuredData.profilePicture = findingUserData.profilePicture || ""; - destrucuredData.bio = findingUserData.bio || ""; - destrucuredData.userName = findingUserData.userName || ""; - destrucuredData.id = String(findingUserData._id) || ""; - destrucuredData.name = findingUserData.name || ""; - destrucuredData.school = findingUserData.school || ""; - destrucuredData.owner = findingUserData.owner || false; - destrucuredData.createdAt = dayjs(findingUserData.createdAt) || ""; - destrucuredData.role = findingUserData.roles.roleType || ""; + return destrucuredData; } } diff --git a/src/utils/getSystemSpecs.ts b/src/utils/getSystemSpecs.ts index 0d523fc..ea09e18 100644 --- a/src/utils/getSystemSpecs.ts +++ b/src/utils/getSystemSpecs.ts @@ -15,6 +15,19 @@ interface DiskUsage { freeStorage: number; } +interface SystemSpecs { + id: number; + type: string; + usage: string | number; // Adjust according to actual types for 'usage' + data: SystemData[]; +} + +interface SystemData { + _id: number; + title: string; + amount: string | number; // Adjust according to actual types for 'amount' +} + function getPrimaryDiskPath(): string { if (os.platform() === "win32") { return "C:"; @@ -33,7 +46,7 @@ function formatBytes(bytes: number): string { return `${formattedValue} ${sizes[i]}`; } -async function getCpuUsage(): Promise { +async function getCpuUsage(): Promise { try { const sys = await si.currentLoad(); return sys; @@ -72,7 +85,7 @@ function getDiskUsage(path: string): Promise { }); } -async function updateSystemSpecs(): Promise { +async function updateSystemSpecs(): Promise { try { const systemUsage = await getSystemUsage(); const diskUsage = await getDiskUsage(getPrimaryDiskPath()); diff --git a/src/utils/logger.ts b/src/utils/logger.ts index 907f0bc..d723af0 100644 --- a/src/utils/logger.ts +++ b/src/utils/logger.ts @@ -11,7 +11,7 @@ type loggerTypes = | "ready"; interface LoggerType { - log(message?: any, optionalParams?: loggerTypes): void; + log(message?: string, optionalParams?: loggerTypes): void; } export default class Logger { log(content: string, type: loggerTypes = "log") { diff --git a/src/websocket/v1/home.ts b/src/websocket/v1/home.ts index 48af8cb..d2c0d6e 100644 --- a/src/websocket/v1/home.ts +++ b/src/websocket/v1/home.ts @@ -5,6 +5,8 @@ import userDataDb from "../../schema/userData"; import Crypto from "node:crypto"; import broadcastMessage from "../../schema/broadcastMessage"; import eventDataSchema from "../../schema/eventData"; +import { AppTypes } from "../../structures/App"; +import { Socket as BaseSocket } from "socket.io"; interface State { authenticated: boolean | null; @@ -12,9 +14,13 @@ interface State { token: string | null; } +interface Socket extends BaseSocket { + sessionId: string; // Define the 'sessionId' property +} + export default { name: "/home", - async run(client: any, socket: any, req: any, params: any) { + async run(client: AppTypes, socket: Socket, req: any, params: any) { const state: State = { authenticated: null, id: null, token: null }; const sendMessage = async function (data: any) { diff --git a/src/websocket/v1/public.ts b/src/websocket/v1/public.ts index fa32f58..8515f85 100644 --- a/src/websocket/v1/public.ts +++ b/src/websocket/v1/public.ts @@ -4,10 +4,16 @@ import dayjs from "dayjs"; import userDataDb from "../../schema/userData"; import Crypto from "node:crypto"; import broadcastMessage from "../../schema/broadcastMessage"; +import { AppTypes } from "../../structures/App"; +import { Socket as BaseSocket } from "socket.io"; + +interface Socket extends BaseSocket { + sessionId: string; // Define the 'sessionId' property +} export default { name: "/public", - async run(client: any, socket: any, req: any, params: any) { + async run(client: AppTypes, socket: Socket, req: any, params: any) { const sendMessage = async function (data: any) { socket.emit("server-message", data); };