refactor(simulator): switch utils to internal module export/import
[e-mobility-charging-stations-simulator.git] / src / utils / FileUtils.ts
CommitLineData
130783a7 1import fs from 'node:fs';
8114d10e
JB
2
3import chalk from 'chalk';
4
60a74391 5import { Utils, logger } from './internal';
268a74bb 6import type { EmptyObject, FileType, HandleErrorParams, JsonType } from '../types';
23132a44 7
268a74bb 8export class FileUtils {
d5bd1c00
JB
9 private constructor() {
10 // This is intentional
11 }
12
9d7484a4 13 public static watchJsonFile<T extends JsonType>(
a95873d8 14 file: string,
7164966d
JB
15 fileType: FileType,
16 logPrefix: string,
9d7484a4 17 refreshedVariable?: T,
a95873d8 18 listener: fs.WatchListener<string> = (event, filename) => {
5a2a53cf 19 if (Utils.isNotEmptyString(filename) && event === 'change') {
a95873d8 20 try {
cca3d474 21 logger.debug(`${logPrefix} ${fileType} file ${file} have changed, reload`);
9d7484a4 22 refreshedVariable && (refreshedVariable = JSON.parse(fs.readFileSync(file, 'utf8')) as T);
a95873d8 23 } catch (error) {
7164966d 24 FileUtils.handleFileException(file, fileType, error as NodeJS.ErrnoException, logPrefix, {
a95873d8
JB
25 throwError: false,
26 });
27 }
28 }
29 }
1895299d 30 ): fs.FSWatcher | undefined {
5a2a53cf 31 if (Utils.isNotEmptyString(file)) {
a95873d8 32 try {
9d7484a4 33 return fs.watch(file, listener);
a95873d8 34 } catch (error) {
7164966d 35 FileUtils.handleFileException(file, fileType, error as NodeJS.ErrnoException, logPrefix, {
a95873d8
JB
36 throwError: false,
37 });
38 }
39 } else {
40 logger.info(`${logPrefix} No ${fileType} file to watch given. Not monitoring its changes`);
41 }
42 }
43
9d7484a4 44 public static handleFileException(
a95873d8 45 file: string,
7164966d 46 fileType: FileType,
e7aeea18 47 error: NodeJS.ErrnoException,
7164966d 48 logPrefix: string,
e7aeea18
JB
49 params: HandleErrorParams<EmptyObject> = { throwError: true, consoleOut: false }
50 ): void {
5a2a53cf 51 const prefix = Utils.isNotEmptyString(logPrefix) ? `${logPrefix} ` : '';
6d8b0b0e
JB
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);
23132a44 69 } else {
6d8b0b0e
JB
70 logger.warn(`${prefix}${logMsg}`, error);
71 }
72 if (params?.throwError) {
73 throw error;
23132a44
JB
74 }
75 }
76}