-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathhelpers.ts
More file actions
146 lines (122 loc) · 3.99 KB
/
helpers.ts
File metadata and controls
146 lines (122 loc) · 3.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
import { Type } from '@nestjs/common';
import { plainToInstance } from 'class-transformer';
import { validateSync, ValidationError } from 'class-validator';
import * as pc from 'picocolors';
import { GenericClass } from '../interfaces';
import { Arr } from './array';
import { InternalLogger } from './logger';
import { Obj } from './object';
import { Str } from './string';
import { readFileSync } from 'fs-extra';
import { join } from 'path';
import { findProjectRoot } from './path';
export const isEmpty = (value: any) => {
if (Str.isString(value)) return value === '';
if (Arr.isArray(value)) return !value.length;
if (Obj.isObj(value)) return Obj.isEmpty(value);
if (Number.isNaN(value) || value === undefined) return true;
return false;
};
export const isBoolean = (value: any): boolean => typeof value === 'boolean';
export const toBoolean = (value: any) => {
const val = String(value);
return [true, 'yes', 'on', '1', 1, 'true'].includes(val?.toLowerCase());
};
export const joinUrl = (url: string, appendString: string): string => {
return url.endsWith('/') ? `${url}${appendString}` : `${url}/${appendString}`;
};
export const logTime = (time: number): string => {
return pc.yellow(`+${time}ms`);
};
export const getTimestampForLog = (): string => {
const timestamp = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: true,
}).format(new Date());
return pc.bgGreen(pc.black(' ' + timestamp + ' '));
};
export const validateOptions = (
payload: Record<string, any>,
schema: Type<GenericClass>,
meta: Record<string, any> = {},
): void => {
const dto = plainToInstance(schema, payload);
const errors = validateSync(dto);
let bag = {};
for (const error of errors) {
const errorsFromParser = parseError(error);
const childErrorBag = {};
for (const key in errorsFromParser) {
if (!isEmpty(errorsFromParser[key])) {
childErrorBag[key] = errorsFromParser[key];
}
}
bag = { ...bag, ...childErrorBag };
}
const keys = Object.keys(bag);
if (!keys.length) return;
const errorStatement = [];
for (const key in bag) {
errorStatement.push(
`${pc.bold(pc.yellow(key))} ${pc.dim(
pc.white('[' + bag[key].join(', ') + ']'),
)}`,
);
}
InternalLogger.error(
meta.cls,
`The config is missing some required options - ${errorStatement.join(', ')}`,
);
};
const parseError = (error: ValidationError) => {
const children = [];
for (const child of error.children || []) {
children.push(parseError(child));
}
const messages = Object.values(error.constraints || {}).map(m =>
Str.replace(m, error.property, Str.title(error.property)),
);
const errors = {};
if (!isEmpty(messages)) {
errors[error.property] = messages;
}
for (const child of children) {
for (const key in child) {
errors[`${error.property}.${key}`] = child[key];
}
}
return errors;
};
export const getTime = () => {
const date = new Date();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
const ampm = hours >= 12 ? 'PM' : 'AM';
const formattedHours = hours % 12 || 12;
const formattedMinutes = minutes.toString().padStart(2, '0');
const formattedSeconds = seconds.toString().padStart(2, '0');
return `${formattedHours}:${formattedMinutes}:${formattedSeconds} ${ampm}`;
};
export const isUndefined = (val: any) => {
return val === undefined;
};
export const isClass = (obj: any) => {
// First check if it's an object and not null
if (obj === null || typeof obj !== 'object') {
return false;
}
// Check if the constructor is not the Object constructor
// This tells us if it was created by a class or Object literal
return Object.getPrototypeOf(obj).constructor.name !== 'Object';
};
export const getPackageJson = () => {
return JSON.parse(
readFileSync(join(findProjectRoot(), 'package.json')).toString(),
);
};