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