3 import { FileType
} from
'../types/FileType';
4 import FileUtils from
'../utils/FileUtils';
5 import logger from
'../utils/Logger';
6 import Utils from
'../utils/Utils';
8 export default class AuthorizedTagsCache
{
9 private static instance
: AuthorizedTagsCache
| null = null;
10 private readonly tagsCaches
: Map
<string, string[]>;
11 private readonly FSWatchers
: Map
<string, fs
.FSWatcher
>;
13 private constructor() {
14 this.tagsCaches
= new Map
<string, string[]>();
15 this.FSWatchers
= new Map
<string, fs
.FSWatcher
>();
18 public static getInstance(): AuthorizedTagsCache
{
19 if (AuthorizedTagsCache
.instance
=== null) {
20 AuthorizedTagsCache
.instance
= new AuthorizedTagsCache();
22 return AuthorizedTagsCache
.instance
;
25 public getAuthorizedTags(file
: string): string[] {
26 if (this.hasTags(file
) === false) {
27 this.setTags(file
, this.getAuthorizedTagsFromFile(file
));
28 // Monitor authorization file
29 this.FSWatchers
.has(file
) === false &&
32 FileUtils
.watchJsonFile(
34 FileType
.Authorization
,
37 (event
, filename
) => {
38 if (filename
&& event
=== 'change') {
41 this.logPrefix(file
) +
43 FileType
.Authorization
+
44 ' file have changed, reload'
46 this.deleteTags(file
);
47 this.deleteFSWatcher(file
);
49 FileUtils
.handleFileException(
51 FileType
.Authorization
,
53 error
as NodeJS
.ErrnoException
,
64 return this.getTags(file
);
67 public deleteAuthorizedTags(file
: string): boolean {
68 return this.deleteTags(file
);
71 private hasTags(file
: string): boolean {
72 return this.tagsCaches
.has(file
);
75 private setTags(file
: string, tags
: string[]) {
76 return this.tagsCaches
.set(file
, tags
);
79 private getTags(file
: string): string[] {
80 return this.tagsCaches
.get(file
);
83 private deleteTags(file
: string): boolean {
84 return this.tagsCaches
.delete(file
);
87 private deleteFSWatcher(file
: string): boolean {
88 this.FSWatchers
.get(file
).close();
89 return this.FSWatchers
.delete(file
);
92 private getAuthorizedTagsFromFile(file
: string): string[] {
93 let authorizedTags
: string[] = [];
96 // Load authorization file
97 authorizedTags
= JSON
.parse(fs
.readFileSync(file
, 'utf8')) as string[];
99 FileUtils
.handleFileException(
100 this.logPrefix(file
),
101 FileType
.Authorization
,
103 error
as NodeJS
.ErrnoException
107 logger
.info(this.logPrefix(file
) + ' No authorization file given)');
109 return authorizedTags
;
112 private logPrefix(file
: string): string {
113 return Utils
.logPrefix(` Authorized tags cache for authorization file '${file}' |`);