Skip to content

Commit

Permalink
fixed package.json location; ready for dist
Browse files Browse the repository at this point in the history
  • Loading branch information
jerryOluranti committed Aug 4, 2022
1 parent 2a77b8c commit 1cd930b
Show file tree
Hide file tree
Showing 17 changed files with 314 additions and 30 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ typings/

# Nuxt.js build / generate output
.nuxt
dist
# dist

# Gatsby files
.cache/
Expand Down
54 changes: 54 additions & 0 deletions dist/catch/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.catchSyncNoReturn = exports.catchSync = exports.catchAsyncNoReturn = exports.catchAsync = void 0;
const tslib_1 = require("tslib");
const logger_1 = require("../logger");
function catchAsync(resolve, cb, _throw = false) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
return (yield resolve);
}
catch (err) {
return handleError(err, cb, _throw);
}
});
}
exports.catchAsync = catchAsync;
function catchAsyncNoReturn(resolve, cb, _throw = false) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
yield resolve;
}
catch (err) {
handleError(err, cb);
}
});
}
exports.catchAsyncNoReturn = catchAsyncNoReturn;
function catchSync(result, cb, _throw = false) {
try {
return result;
}
catch (err) {
return handleError(err, cb);
}
}
exports.catchSync = catchSync;
function catchSyncNoReturn(result, cb, _throw = false) {
try {
result;
}
catch (err) {
handleError(err, cb);
}
}
exports.catchSyncNoReturn = catchSyncNoReturn;
function handleError(err, _throw, cb) {
const error = new Error(err.message);
(0, logger_1.logError)(error);
if (cb)
cb(err);
if (_throw)
throw new Error(err.message);
return undefined;
}
30 changes: 30 additions & 0 deletions dist/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
export interface ILoggerConfig {
logName: string,
logPath: string,
maxSize?: number,
logToFile: boolean
}

export interface IQueryFactory {
size: number;
lastLogTime: number | undefined;
logs: Array<Log>;
get: () => Array<Log>;
parse: (logBuffer: Buffer) => void;
head: (length: number) => Array<Log>;
tail: (length: number) => Array<Log>;
findByTimeStamp: (timestamp: number) => Log | undefined;
findByTimeRange: (startTime: number, stopTime: number) => IQueryFactory;
findByErrorLevel: (level: ErrorLevel) => IQueryFactory;
findByStack: (stack: string) => IQueryFactory;
findByErrorMessage: (message: string) => IQueryFactory;
}

export interface Log {
timestamp: number;
level: ErrorLevel;
stack: string;
message: string;
}

export declare type ErrorLevel = "INFO" | "WARN" | "LOW" | "MODERATE" | "HIGH" | "EMERGENCY"
35 changes: 35 additions & 0 deletions dist/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.config = void 0;
const tslib_1 = require("tslib");
const process_1 = require("process");
require("dotenv").config();
function init() {
var _a, _b;
let config;
try {
let path = "";
if (process.env.MODE === "DEVELOPMENT") {
path = "../package.json";
}
else {
if ((0, process_1.cwd)().includes("node_modules")) {
path = (0, process_1.cwd)().split("node_modules")[0].concat("package.json");
}
}
config = require(path).trollerConfig;
}
catch (err) {
config = undefined;
console.log("Could not read config from package.json. Using default config...");
}
return {
logName: (_a = config === null || config === void 0 ? void 0 : config.logName) !== null && _a !== void 0 ? _a : "test.log",
logPath: process.env.MODE !== "DEVELOPMENT" ? `${(0, process_1.cwd)().split("node_modules")[0]}/logs/` : "/logs/",
logToFile: (_b = config === null || config === void 0 ? void 0 : config.logToFile) !== null && _b !== void 0 ? _b : true,
};
}
exports.config = init();
tslib_1.__exportStar(require("./logger"), exports);
tslib_1.__exportStar(require("./catch"), exports);
tslib_1.__exportStar(require("./query"), exports);
37 changes: 37 additions & 0 deletions dist/logger/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.logConsole = exports.logError = void 0;
const node_fs_1 = require("node:fs");
const __1 = require("../");
const datetime_1 = require("../utils/datetime");
function logError(err) {
if (!err)
return;
logLocal(err);
}
exports.logError = logError;
function logMessage(err) {
var _a, _b;
const logLineDetails = (_b = (_a = err === null || err === void 0 ? void 0 : err.stack) === null || _a === void 0 ? void 0 : _a.split("at ")[1]) === null || _b === void 0 ? void 0 : _b.trim();
return Buffer.from(`[${(0, datetime_1.formatDateTime)(Date.now())}] => ISSUE, Stack: ${logLineDetails}, ${err}\n`, "utf-8");
}
function logLocal(err) {
let newLog = logMessage(err);
if (!__1.config.logToFile)
return;
let logs = Buffer.from([]);
try {
logs = (0, node_fs_1.readFileSync)(__1.config.logPath + __1.config.logName);
}
catch (err) {
if (!(0, node_fs_1.existsSync)(__1.config.logPath))
(0, node_fs_1.mkdirSync)(__1.config.logPath);
logs = Buffer.from(`---- LOG HEAD | START DATE: ${(0, datetime_1.formatDateTime)(Date.now())}} ----\n`, "utf-8");
}
newLog = Buffer.concat([logs, newLog]);
(0, node_fs_1.writeFileSync)(__1.config.logPath + __1.config.logName, newLog);
}
function logConsole(message) {
console.log(message);
}
exports.logConsole = logConsole;
84 changes: 84 additions & 0 deletions dist/query/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Query = void 0;
const tslib_1 = require("tslib");
const promises_1 = require("fs/promises");
const __1 = require("..");
const catch_1 = require("../catch");
const datetime_1 = require("../utils/datetime");
class Query {
constructor(logPath) {
this.logPath = logPath;
this.node = new QueryFactory();
this.logPath = logPath || __1.config.logPath;
this.readFileToBuffer();
}
;
readFileToBuffer() {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const data = yield (0, catch_1.catchAsync)((0, promises_1.readFile)(this.logPath));
this.node.parse(data);
});
}
}
exports.Query = Query;
class QueryFactory {
constructor() {
this.size = 0;
this.logs = [];
this.temp = [];
}
get() {
const _temp = this.temp;
this.temp = [];
return _temp;
}
parse(logBuffer) {
var _a;
let buf = logBuffer.toString().split('\n').reverse();
buf.pop();
buf = buf.reverse();
this.logs = buf.map(log => {
const parsedLog = log.split(",");
return {
timestamp: (0, datetime_1.parseDateTime)(parsedLog[0].split("=>")[0].trim().replace('[', '').replace(']', '')),
level: parsedLog[0].split("=>")[1].trim(),
stack: parsedLog[1].trim(),
message: parsedLog[2].trim()
};
});
this.size = this.logs.length;
this.lastLogTime = ((_a = this.logs.at(-1)) === null || _a === void 0 ? void 0 : _a.timestamp) || undefined;
}
head(length = 5) {
return this.logs.slice(0, length + 1);
}
tail(length = 5) {
return this.logs.slice(this.logs.length - length + 1);
}
findByTimeStamp(timestamp) {
return this.logs.find(log => log.timestamp === timestamp);
}
findByTimeRange(startTime, stopTime = 0) {
if (startTime <= 0)
throw new Error("Invalid startTime value");
if (stopTime === 0) {
this.temp = (this.temp || this.logs).filter(log => log.timestamp >= startTime);
return this;
}
this.temp = (this.temp || this.logs).filter(log => log.timestamp >= startTime && log.timestamp <= stopTime);
return this;
}
findByErrorLevel(level) {
this.temp = (this.temp || this.logs).filter(log => log.level === level);
return this;
}
findByErrorMessage(message) {
this.temp = (this.temp || this.logs).filter(log => log.message.includes(message));
return this;
}
findByStack(stack) {
this.temp = (this.temp || this.logs).filter((log) => log.stack.includes(stack));
return this;
}
}
26 changes: 26 additions & 0 deletions dist/utils/datetime.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseDateTime = exports.formatDateTime = void 0;
function formatDateTime(timestamp) {
const date = new Date(timestamp);
const day = date.getDate();
const month = date.getMonth();
const year = date.getFullYear();
const hour = date.getHours();
const mins = date.getMinutes();
const secs = date.getSeconds();
const mm = month + 1 > 9 ? month + 1 : `0${month + 1}`;
const dd = day > 9 ? day : `0${day}`;
const hh = hour > 9 ? hour : `0${hour}`;
const _mins = mins > 9 ? mins : `0${mins}`;
const _secs = secs > 9 ? secs : `0${secs}`;
return `${year}-${mm}-${dd} ${hh}:${_mins}:${_secs}`;
}
exports.formatDateTime = formatDateTime;
function parseDateTime(str) {
const timestamp = Date.parse(str.replaceAll(" ", "T"));
if (timestamp === 0 || isNaN(timestamp))
throw new Error("Unable to parse datetime string; Invalid string format. [yyyy/mm/dd, hh:mm:ss]");
return timestamp;
}
exports.parseDateTime = parseDateTime;
8 changes: 6 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
"license": "MIT",
"private": true,
"scripts": {
"start:dev": "export NODE_ENV=DEVELOPMENT && ts-node src/index.ts",
"start": "export MODE=PRODUCTION && ts-node src/index.ts",
"start:dev": "export MODE=DEVELOPMENT && ts-node src/index.ts",
"compile": "tsc && cp types/index.d.ts dist/",
"test": "jest src/tests/test.spec.ts"
},
"dependencies": {
Expand All @@ -22,5 +24,7 @@
"ts-node": "^10.7.0",
"tslib": "^2.3.1"
},
"trollerConfig": {}
"trollerConfig": {
"logName": "testfrompkg.log"
}
}
Binary file modified src/.DS_Store
Binary file not shown.
File renamed without changes.
Binary file removed src/handler/.DS_Store
Binary file not shown.
31 changes: 20 additions & 11 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,38 @@
import { cwd } from "process";
import {ILoggerConfig} from "@types";
require("dotenv").config();

function validateConfig(): ILoggerConfig {
const configPath = process.env.NODE_ENV === "DEVELOPMENT" ? "../package.json" : "../../../package.json";
const logPath = "./src/logs/";
function init(): ILoggerConfig {
let config: ILoggerConfig | undefined;

try {
config = require(configPath).trollerConfig;
let path = "";
if (process.env.MODE === "DEVELOPMENT") {
path = "../package.json";
}else {
if(cwd().includes("node_modules")) {
path = cwd().split("node_modules")[0].concat("package.json");
}
}
config = require(path).trollerConfig;
} catch(err) {
config = undefined;
// console.log("Could not find config; Using default values...");
console.log("Could not read config from package.json. Using default config...");
}

return {
logName: config?.logName ?? "test.log",
logPath: config?.logPath ? `../../..${config?.logPath}/logs/` : logPath,
logToFile: config?.logToFile ?? true
logPath: process.env.MODE !== "DEVELOPMENT" ? `${cwd().split("node_modules")[0]}/logs/` : "/logs/",
logToFile: config?.logToFile ?? true,
};
}

export const config = validateConfig();
// const cfg = init();
export const config = init();
// export const config = cfg;

export * from "./logger";
export * from "./handler";
export * from "./catch";
export * from "./query";

// console.log(validateConfig());
// console.log(cfg);
2 changes: 1 addition & 1 deletion src/query/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { readFile } from "fs/promises";
import { config } from "..";
import { catchAsync } from "../handler";
import { catchAsync } from "../catch";
import { IQueryFactory, Log, ErrorLevel } from "@types";
import { parseDateTime } from "../utils/datetime";

Expand Down
5 changes: 3 additions & 2 deletions src/tests/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { cwd } from "node:process";
import { config } from "../index";

export function initTestSuite() {
Expand All @@ -7,8 +8,8 @@ export function initTestSuite() {

it("should have valid config values", () => {
expect(config).toBeDefined();
expect(config.logName).toEqual("test.log");
expect(config.logPath).toEqual("./src/logs/");
expect(typeof config.logName).toBe('string');
expect(config.logPath).toEqual(process.env.MODE === "DEVELOPMENT" ? "/logs/" : `${cwd().split("node_modules")[0]}/logs/`);
expect(config.logToFile).toBeTruthy();
});
}
Loading

0 comments on commit 1cd930b

Please sign in to comment.