perf(simulator): optimize tags cache
[e-mobility-charging-stations-simulator.git] / src / charging-station / AuthorizedTagsCache.ts
index 0f702047702ce5cc92890f28679a9cafddacf1fc..48c72fd4bb2399d8bdd199bc016c0085c7a32711 100644 (file)
@@ -1,18 +1,19 @@
-import fs from 'fs';
+import fs from 'node:fs';
 
-import { FileType } from '../types/FileType';
-import FileUtils from '../utils/FileUtils';
-import logger from '../utils/Logger';
-import Utils from '../utils/Utils';
+import { FileType } from '../types';
+import { FileUtils, Utils, logger } from '../utils';
 
-export default class AuthorizedTagsCache {
+type TagsCacheValueType = {
+  tags: string[];
+  tagsFileWatcher: fs.FSWatcher | undefined;
+};
+
+export class AuthorizedTagsCache {
   private static instance: AuthorizedTagsCache | null = null;
-  private readonly tagsCaches: Map<string, string[]>;
-  private readonly FSWatchers: Map<string, fs.FSWatcher>;
+  private readonly tagsCaches: Map<string, TagsCacheValueType>;
 
   private constructor() {
-    this.tagsCaches = new Map<string, string[]>();
-    this.FSWatchers = new Map<string, fs.FSWatcher>();
+    this.tagsCaches = new Map<string, TagsCacheValueType>();
   }
 
   public static getInstance(): AuthorizedTagsCache {
@@ -22,44 +23,9 @@ export default class AuthorizedTagsCache {
     return AuthorizedTagsCache.instance;
   }
 
-  public getAuthorizedTags(file: string): string[] {
+  public getAuthorizedTags(file: string): string[] | undefined {
     if (this.hasTags(file) === false) {
       this.setTags(file, this.getAuthorizedTagsFromFile(file));
-      // Monitor authorization file
-      this.FSWatchers.has(file) === false &&
-        this.FSWatchers.set(
-          file,
-          FileUtils.watchJsonFile(
-            this.logPrefix(file),
-            FileType.Authorization,
-            file,
-            null,
-            (event, filename) => {
-              if (filename && event === 'change') {
-                try {
-                  logger.debug(
-                    this.logPrefix(file) +
-                      ' ' +
-                      FileType.Authorization +
-                      ' file have changed, reload'
-                  );
-                  this.deleteTags(file);
-                  this.deleteFSWatcher(file);
-                } catch (error) {
-                  FileUtils.handleFileException(
-                    this.logPrefix(file),
-                    FileType.Authorization,
-                    file,
-                    error as NodeJS.ErrnoException,
-                    {
-                      throwError: false,
-                    }
-                  );
-                }
-              }
-            }
-          )
-        );
     }
     return this.getTags(file);
   }
@@ -73,22 +39,46 @@ export default class AuthorizedTagsCache {
   }
 
   private setTags(file: string, tags: string[]) {
-    return this.tagsCaches.set(file, tags);
+    return this.tagsCaches.set(file, {
+      tags,
+      tagsFileWatcher: FileUtils.watchJsonFile(
+        file,
+        FileType.Authorization,
+        this.logPrefix(file),
+        undefined,
+        (event, filename) => {
+          if (Utils.isNotEmptyString(filename) && event === 'change') {
+            try {
+              logger.debug(
+                `${this.logPrefix(file)} ${FileType.Authorization} file have changed, reload`
+              );
+              this.deleteTags(file);
+            } catch (error) {
+              FileUtils.handleFileException(
+                file,
+                FileType.Authorization,
+                error as NodeJS.ErrnoException,
+                this.logPrefix(file),
+                {
+                  throwError: false,
+                }
+              );
+            }
+          }
+        }
+      ),
+    });
   }
 
-  private getTags(file: string): string[] {
-    return this.tagsCaches.get(file);
+  private getTags(file: string): string[] | undefined {
+    return this.tagsCaches.get(file)?.tags;
   }
 
   private deleteTags(file: string): boolean {
+    this.tagsCaches.get(file)?.tagsFileWatcher?.close();
     return this.tagsCaches.delete(file);
   }
 
-  private deleteFSWatcher(file: string): boolean {
-    this.FSWatchers.get(file).close();
-    return this.FSWatchers.delete(file);
-  }
-
   private getAuthorizedTagsFromFile(file: string): string[] {
     let authorizedTags: string[] = [];
     if (file) {
@@ -97,19 +87,19 @@ export default class AuthorizedTagsCache {
         authorizedTags = JSON.parse(fs.readFileSync(file, 'utf8')) as string[];
       } catch (error) {
         FileUtils.handleFileException(
-          this.logPrefix(file),
-          FileType.Authorization,
           file,
-          error as NodeJS.ErrnoException
+          FileType.Authorization,
+          error as NodeJS.ErrnoException,
+          this.logPrefix(file)
         );
       }
     } else {
-      logger.info(this.logPrefix(file) + ' No authorization file given)');
+      logger.info(`${this.logPrefix(file)} No authorization file given`);
     }
     return authorizedTags;
   }
 
-  private logPrefix(file: string): string {
+  private logPrefix = (file: string): string => {
     return Utils.logPrefix(` Authorized tags cache for authorization file '${file}' |`);
-  }
+  };
 }