-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhelpers.ts
More file actions
77 lines (62 loc) · 2.22 KB
/
helpers.ts
File metadata and controls
77 lines (62 loc) · 2.22 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
import * as fsp from "node:fs/promises";
import * as path from "node:path";
import { ConsoleLogger, type DefaultLogger } from "@hunteroi/advanced-logger";
const console = new ConsoleLogger();
export async function readFilesFrom<T>(
directory: string,
callback: (name: string, props: T) => void,
logger: DefaultLogger = console,
): Promise<void> {
try {
logger.debug(`Lecture du répertoire ${directory}`);
const files = await fsp.readdir(directory);
for (const file of files) {
const filePath = path.join(directory, file);
const stats = await fsp.stat(filePath);
if (stats.isDirectory()) {
await readFilesFrom(filePath, callback, logger);
continue;
}
if (stats.isFile() && !file.endsWith(".ts")) continue;
logger.debug(`Lecture du fichier ${filePath}`);
const props = await import(filePath);
callback(file.replace(".ts", ""), props.default as T);
}
} catch (err) {
logger.error(getErrorMessage(err));
}
}
// biome-ignore lint/suspicious/noExplicitAny: evaluated code is of type "any"
export function clean(text: any): string {
if (typeof text === "string") {
return text.replace(/@/g, "@");
}
return text;
}
// #region Error handling helper
// source: https://kentcdodds.com/blog/get-a-catch-block-error-message-with-typescript
type ErrorWithMessage = {
message: string;
};
function isErrorWithMessage(error: unknown): error is ErrorWithMessage {
return (
typeof error === "object" &&
error !== null &&
"message" in error &&
typeof (error as Record<string, unknown>).message === "string"
);
}
function toErrorWithMessage(maybeError: unknown): ErrorWithMessage {
if (isErrorWithMessage(maybeError)) return maybeError;
try {
return new Error(JSON.stringify(maybeError));
} catch {
// fallback in case there's an error stringifying the maybeError
// like with circular references for example.
return new Error(String(maybeError));
}
}
export function getErrorMessage(error: unknown): string {
return toErrorWithMessage(error).message;
}
// #endregion