refactor(simulator): switch utils to internal module export/import
[e-mobility-charging-stations-simulator.git] / src / utils / FileUtils.ts
1 import fs from 'node:fs';
2
3 import chalk from 'chalk';
4
5 import { Utils, logger } from './internal';
6 import type { EmptyObject, FileType, HandleErrorParams, JsonType } from '../types';
7
8 export class FileUtils {
9 private constructor() {
10 // This is intentional
11 }
12
13 public static watchJsonFile<T extends JsonType>(
14 file: string,
15 fileType: FileType,
16 logPrefix: string,
17 refreshedVariable?: T,
18 listener: fs.WatchListener<string> = (event, filename) => {
19 if (Utils.isNotEmptyString(filename) && event === 'change') {
20 try {
21 logger.debug(`${logPrefix} ${fileType} file ${file} have changed, reload`);
22 refreshedVariable && (refreshedVariable = JSON.parse(fs.readFileSync(file, 'utf8')) as T);
23 } catch (error) {
24 FileUtils.handleFileException(file, fileType, error as NodeJS.ErrnoException, logPrefix, {
25 throwError: false,
26 });
27 }
28 }
29 }
30 ): fs.FSWatcher | undefined {
31 if (Utils.isNotEmptyString(file)) {
32 try {
33 return fs.watch(file, listener);
34 } catch (error) {
35 FileUtils.handleFileException(file, fileType, error as NodeJS.ErrnoException, logPrefix, {
36 throwError: false,
37 });
38 }
39 } else {
40 logger.info(`${logPrefix} No ${fileType} file to watch given. Not monitoring its changes`);
41 }
42 }
43
44 public static handleFileException(
45 file: string,
46 fileType: FileType,
47 error: NodeJS.ErrnoException,
48 logPrefix: string,
49 params: HandleErrorParams<EmptyObject> = { throwError: true, consoleOut: false }
50 ): void {
51 const prefix = Utils.isNotEmptyString(logPrefix) ? `${logPrefix} ` : '';
52 let logMsg: string;
53 switch (error.code) {
54 case 'ENOENT':
55 logMsg = `${fileType} file ${file} not found:`;
56 break;
57 case 'EEXIST':
58 logMsg = `${fileType} file ${file} already exists:`;
59 break;
60 case 'EACCES':
61 logMsg = `${fileType} file ${file} access denied:`;
62 break;
63 default:
64 logMsg = `${fileType} file ${file} error:`;
65 }
66 if (params?.consoleOut) {
67 logMsg = `${logMsg} `;
68 console.warn(`${chalk.green(prefix)}${chalk.yellow(logMsg)}`, error);
69 } else {
70 logger.warn(`${prefix}${logMsg}`, error);
71 }
72 if (params?.throwError) {
73 throw error;
74 }
75 }
76 }