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