Add date, log and number utils

This commit is contained in:
Sambo Chea 2021-09-13 18:34:26 +07:00
parent df1f0eb101
commit 9d1e61efc7
7 changed files with 162 additions and 5042 deletions

1
.gitignore vendored
View File

@ -118,3 +118,4 @@ dist
.yarn/install-state.gz .yarn/install-state.gz
.pnp.* .pnp.*
package-lock.json

5042
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -20,8 +20,10 @@
"author": "Sambo Chea <sombochea@cubetiqs.com>", "author": "Sambo Chea <sombochea@cubetiqs.com>",
"license": "ISC", "license": "ISC",
"devDependencies": { "devDependencies": {
"@types/node": "^16.9.1",
"@typescript-eslint/eslint-plugin": "^4.30.0", "@typescript-eslint/eslint-plugin": "^4.30.0",
"@typescript-eslint/parser": "^4.30.0", "@typescript-eslint/parser": "^4.30.0",
"chalk": "^4.1.2",
"eslint": "^7.32.0", "eslint": "^7.32.0",
"eslint-config-prettier": "^8.3.0", "eslint-config-prettier": "^8.3.0",
"eslint-plugin-jsdoc": "^36.0.8", "eslint-plugin-jsdoc": "^36.0.8",

39
src/date/index.ts Normal file
View File

@ -0,0 +1,39 @@
const dateFormat: any = {
day: "2-digit",
month: "2-digit",
year: "2-digit",
}
const timeFormat: any = {
hour12: true,
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
}
export const formatDate = (date: Date, locale: string = "en-US") => {
return date.toLocaleDateString(locale, {
...dateFormat,
...timeFormat,
})
}
export const formatDateOnly = (date: Date, locale: string = "en-US") => {
return date.toLocaleDateString(locale, dateFormat)
}
export const formatDateFromTimestamp = (
time: number,
locale: string = "en-US"
) => {
return formatDate(new Date(time), locale)
}
export const millisToSeconds = (millis: number) => {
return millis / 1000
}
export const randomThenGetOne = (data: any[]): any => {
const randomIndex = Math.floor(Math.random() * data.length)
return data[randomIndex]
}

44
src/log/index.ts Normal file
View File

@ -0,0 +1,44 @@
import chalk from "chalk"
import { formatDate } from "../date"
import Logger from "./writter"
let logger = Logger.getProvider()
const prefixColor = (
prefix: string,
message?: any,
color: string = "green"
) => {
const timestamp = formatDate(new Date())
if (Logger.isEnabled()) {
return `[${timestamp}] - ${prefix}: ${message}`
}
const firstStep = chalk`[${timestamp}] - {${color} ${prefix}}:`
return `${firstStep} ${message}`
}
export const debug = (message?: any, ...args: any[]) => {
const msg = prefixColor("DEBUG", message, "magentaBright")
args.length === 0 ? logger.log(msg) : logger.log(msg, ...args)
}
export const error = (message?: any, ...args: any[]) => {
const msg = prefixColor("ERROR", message, "red")
args.length === 0 ? logger.error(msg) : logger.error(msg, ...args)
}
export const warn = (message?: any, ...args: any[]) => {
const msg = prefixColor("WARN", message, "yellow")
args.length === 0 ? logger.warn(msg) : logger.warn(msg, ...args)
}
export const info = (message?: any, ...args: any[]) => {
const msg = prefixColor("INFO", message, "cyan")
args.length === 0 ? logger.info(msg) : logger.info(msg, ...args)
}
export const success = (message?: any, ...args: any[]) => {
const msg = prefixColor("SUCCESS", message)
args.length === 0 ? logger.info(msg) : logger.info(msg, ...args)
}

55
src/log/writter.ts Normal file
View File

@ -0,0 +1,55 @@
import * as fs from "fs"
import { Console } from "console"
import * as path from "path"
import { formatDateOnly } from "../date"
class Logger {
private static enabled: boolean = false
public static setEnabled(enabled: boolean): void {
this.enabled = enabled
}
public static isEnabled(): boolean {
return this.enabled
}
private static logDir?: string
public static setLogDir(logDir: string): void {
this.logDir = logDir
}
public static getLogDir(): string | null | undefined {
return this.logDir
}
public static getProvider(): Console {
if (this.isEnabled()) {
const rootPath = path.resolve(this.getLogDir() || "./")
const logPath = `${rootPath}/logs`
if (!fs.existsSync(logPath)) {
fs.mkdirSync(logPath, { recursive: true })
}
const time = formatDateOnly(new Date()).replace(/\//g, "-")
console.log("Logs writing to path =>", logPath)
const output = fs.createWriteStream(
`${logPath}/stdout-${time}.log`,
{
flags: "a",
}
)
const errorOutput = fs.createWriteStream(
`${logPath}/stderr-${time}.log`,
{
flags: "a",
}
)
return new Console({ stdout: output, stderr: errorOutput })
}
return console
}
}
export default Logger

21
src/number/parser.ts Normal file
View File

@ -0,0 +1,21 @@
export const parse2IntOrNull = (val?: any): number | null => {
try {
return Number.parseInt(val)
} catch (ex) {
return null
}
}
export const parse2Int = (val?: any, defaultValue: number = 0): number => {
const parsed = parse2IntOrNull(val)
if (parsed) return parsed
return defaultValue
}
export const parseToBoolean = (
val?: any,
defaultValue: boolean = false
): boolean => {
if (!val) return defaultValue
return val === true || val.toLowerCase() === "true"
}