UNPKG

@ajejoseph22/proxx

Version:

A lightweight HTTPS/HTTP proxy server with bandwidth tracking, basic auth and real-time analytics.

71 lines (70 loc) 3.06 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.DatabaseService = exports.DatabaseError = void 0; const promises_1 = __importDefault(require("fs/promises")); const path_1 = __importDefault(require("path")); const lodash_merge_1 = __importDefault(require("lodash.merge")); class DatabaseError extends Error { constructor(message, cause) { super(message); this.cause = cause; this.name = "DatabaseError"; } } exports.DatabaseError = DatabaseError; class DatabaseService { constructor() { this.data = { auth: {}, metrics: {} }; this.dbPath = process.env.DB_PATH || path_1.default.join(__dirname, "db.json"); } initialize() { return __awaiter(this, void 0, void 0, function* () { try { const dbFileExists = yield promises_1.default .access(this.dbPath) .then(() => true) .catch(() => false); if (!dbFileExists) { console.log("Creating new DB file at ", this.dbPath); yield promises_1.default.writeFile(this.dbPath, JSON.stringify(this.data, null, 2)); } const fileContent = yield promises_1.default.readFile(this.dbPath, "utf-8"); if (!fileContent) yield promises_1.default.writeFile(this.dbPath, JSON.stringify(this.data, null, 2)); else this.data = JSON.parse(fileContent); } catch (error) { throw new DatabaseError("Failed to initialize DB", error); } }); } save(data) { return __awaiter(this, void 0, void 0, function* () { try { const newData = (0, lodash_merge_1.default)({}, this.data, data); yield promises_1.default.writeFile(this.dbPath, JSON.stringify(newData, null, 2)); this.data = newData; } catch (error) { throw new DatabaseError("Failed to save DB", error); } }); } getData() { return Object.assign({}, this.data); } } exports.DatabaseService = DatabaseService;