Rename a type definition
[e-mobility-charging-stations-simulator.git] / src / utils / FileUtils.ts
1 import { JsonType, JsonValue } from '../types/JsonType';
2
3 import { EmptyObject } from '../types/EmptyObject';
4 import { FileType } from '../types/FileType';
5 import { HandleErrorParams } from '../types/Error';
6 import Utils from './Utils';
7 import chalk from 'chalk';
8 import fs from 'fs';
9 import logger from './Logger';
10
11 export default class FileUtils {
12 static watchJsonFile<T extends JsonType | JsonValue>(
13 logPrefix: string,
14 fileType: FileType,
15 file: string,
16 attribute?: T,
17 listener: fs.WatchListener<string> = (event, filename) => {
18 if (filename && event === 'change') {
19 try {
20 logger.debug(logPrefix + ' ' + fileType + ' file ' + file + ' have changed, reload');
21 attribute && (attribute = JSON.parse(fs.readFileSync(file, 'utf8')) as T);
22 } catch (error) {
23 FileUtils.handleFileException(logPrefix, fileType, file, error as NodeJS.ErrnoException, {
24 throwError: false,
25 });
26 }
27 }
28 }
29 ) {
30 if (file) {
31 try {
32 fs.watch(file, listener);
33 } catch (error) {
34 FileUtils.handleFileException(logPrefix, fileType, file, error as NodeJS.ErrnoException, {
35 throwError: false,
36 });
37 }
38 } else {
39 logger.info(`${logPrefix} No ${fileType} file to watch given. Not monitoring its changes`);
40 }
41 }
42
43 static handleFileException(
44 logPrefix: string,
45 fileType: FileType,
46 file: string,
47 error: NodeJS.ErrnoException,
48 params: HandleErrorParams<EmptyObject> = { throwError: true, consoleOut: false }
49 ): void {
50 const prefix = !Utils.isEmptyString(logPrefix) ? logPrefix + ' ' : '';
51 if (error.code === 'ENOENT') {
52 if (params?.consoleOut) {
53 console.warn(
54 chalk.green(prefix) + chalk.yellow(fileType + ' file ' + file + ' not found: '),
55 error
56 );
57 } else {
58 logger.warn(prefix + fileType + ' file ' + file + ' not found: %j', error);
59 }
60 } else if (error.code === 'EEXIST') {
61 if (params?.consoleOut) {
62 console.warn(
63 chalk.green(prefix) + chalk.yellow(fileType + ' file ' + file + ' already exists: '),
64 error
65 );
66 } else {
67 logger.warn(prefix + fileType + ' file ' + file + ' already exists: %j', error);
68 }
69 } else if (error.code === 'EACCES') {
70 if (params?.consoleOut) {
71 console.warn(
72 chalk.green(prefix) + chalk.yellow(fileType + ' file ' + file + ' access denied: '),
73 error
74 );
75 } else {
76 logger.warn(prefix + fileType + ' file ' + file + ' access denied: %j', error);
77 }
78 } else {
79 if (params?.consoleOut) {
80 console.warn(
81 chalk.green(prefix) + chalk.yellow(fileType + ' file ' + file + ' error: '),
82 error
83 );
84 } else {
85 logger.warn(prefix + fileType + ' file ' + file + ' error: %j', error);
86 }
87 if (params?.throwError) {
88 throw error;
89 }
90 }
91 }
92 }