4a9da4ce67f3bfa6e0ca699395f971d1a42712fc
1 import { FileType
} from
'../types/FileType';
2 import FileUtils from
'../utils/FileUtils';
3 import Utils from
'../utils/Utils';
5 import logger from
'../utils/Logger';
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
>;
12 private constructor() {
13 this.tagsCaches
= new Map
<string, string[]>();
14 this.FSWatchers
= new Map
<string, fs
.FSWatcher
>();
17 public static getInstance(): AuthorizedTagsCache
{
18 if (!AuthorizedTagsCache
.instance
) {
19 AuthorizedTagsCache
.instance
= new AuthorizedTagsCache();
21 return AuthorizedTagsCache
.instance
;
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
) &&
31 FileUtils
.watchJsonFile(
33 FileType
.Authorization
,
36 (event
, filename
) => {
37 if (filename
&& event
=== 'change') {
40 this.logPrefix(file
) +
42 FileType
.Authorization
+
43 ' file have changed, reload'
45 this.deleteTags(file
);
46 this.deleteFSWatcher(file
);
48 FileUtils
.handleFileException(
50 FileType
.Authorization
,
52 error
as NodeJS
.ErrnoException
,
63 return this.getTags(file
);
66 private hasTags(file
: string): boolean {
67 return this.tagsCaches
.has(file
);
70 private setTags(file
: string, tags
: string[]) {
71 return this.tagsCaches
.set(file
, tags
);
74 private getTags(file
: string): string[] {
75 return this.tagsCaches
.get(file
);
78 private deleteTags(file
: string): boolean {
79 return this.tagsCaches
.delete(file
);
82 private deleteFSWatcher(file
: string): boolean {
83 this.FSWatchers
.get(file
).close();
84 return this.FSWatchers
.delete(file
);
87 private getAuthorizedTagsFromFile(file
: string): string[] {
88 let authorizedTags
: string[] = [];
91 // Load authorization file
92 authorizedTags
= JSON
.parse(fs
.readFileSync(file
, 'utf8')) as string[];
94 FileUtils
.handleFileException(
96 FileType
.Authorization
,
98 error
as NodeJS
.ErrnoException
102 logger
.info(this.logPrefix(file
) + ' No authorization file given)');
104 return authorizedTags
;
107 private logPrefix(file
: string): string {
108 return Utils
.logPrefix(` Authorized tags cache for authorization file '${file}' |`);