4a9da4ce67f3bfa6e0ca699395f971d1a42712fc
[e-mobility-charging-stations-simulator.git] / src / charging-station / AuthorizedTagsCache.ts
1 import { FileType } from '../types/FileType';
2 import FileUtils from '../utils/FileUtils';
3 import Utils from '../utils/Utils';
4 import fs from 'fs';
5 import logger from '../utils/Logger';
6
7 export default class AuthorizedTagsCache {
8 private static instance: AuthorizedTagsCache | null = null;
9 private readonly tagsCaches: Map<string, string[]>;
10 private readonly FSWatchers: Map<string, fs.FSWatcher>;
11
12 private constructor() {
13 this.tagsCaches = new Map<string, string[]>();
14 this.FSWatchers = new Map<string, fs.FSWatcher>();
15 }
16
17 public static getInstance(): AuthorizedTagsCache {
18 if (!AuthorizedTagsCache.instance) {
19 AuthorizedTagsCache.instance = new AuthorizedTagsCache();
20 }
21 return AuthorizedTagsCache.instance;
22 }
23
24 public getAuthorizedTags(file: string): string[] {
25 if (!this.hasTags(file)) {
26 this.setTags(file, this.getAuthorizedTagsFromFile(file));
27 // Monitor authorization file
28 !this.FSWatchers.has(file) &&
29 this.FSWatchers.set(
30 file,
31 FileUtils.watchJsonFile(
32 this.logPrefix(file),
33 FileType.Authorization,
34 file,
35 null,
36 (event, filename) => {
37 if (filename && event === 'change') {
38 try {
39 logger.debug(
40 this.logPrefix(file) +
41 ' ' +
42 FileType.Authorization +
43 ' file have changed, reload'
44 );
45 this.deleteTags(file);
46 this.deleteFSWatcher(file);
47 } catch (error) {
48 FileUtils.handleFileException(
49 this.logPrefix(file),
50 FileType.Authorization,
51 file,
52 error as NodeJS.ErrnoException,
53 {
54 throwError: false,
55 }
56 );
57 }
58 }
59 }
60 )
61 );
62 }
63 return this.getTags(file);
64 }
65
66 private hasTags(file: string): boolean {
67 return this.tagsCaches.has(file);
68 }
69
70 private setTags(file: string, tags: string[]) {
71 return this.tagsCaches.set(file, tags);
72 }
73
74 private getTags(file: string): string[] {
75 return this.tagsCaches.get(file);
76 }
77
78 private deleteTags(file: string): boolean {
79 return this.tagsCaches.delete(file);
80 }
81
82 private deleteFSWatcher(file: string): boolean {
83 this.FSWatchers.get(file).close();
84 return this.FSWatchers.delete(file);
85 }
86
87 private getAuthorizedTagsFromFile(file: string): string[] {
88 let authorizedTags: string[] = [];
89 if (file) {
90 try {
91 // Load authorization file
92 authorizedTags = JSON.parse(fs.readFileSync(file, 'utf8')) as string[];
93 } catch (error) {
94 FileUtils.handleFileException(
95 this.logPrefix(file),
96 FileType.Authorization,
97 file,
98 error as NodeJS.ErrnoException
99 );
100 }
101 } else {
102 logger.info(this.logPrefix(file) + ' No authorization file given)');
103 }
104 return authorizedTags;
105 }
106
107 private logPrefix(file: string): string {
108 return Utils.logPrefix(` Authorized tags cache for authorization file '${file}' |`);
109 }
110 }