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)} ${FileType.Authorization} file have changed, reload`
43 this.deleteTags(file
);
44 this.deleteFSWatcher(file
);
46 FileUtils
.handleFileException(
48 FileType
.Authorization
,
50 error
as NodeJS
.ErrnoException
,
61 return this.getTags(file
);
64 public deleteAuthorizedTags(file
: string): boolean {
65 return this.deleteTags(file
);
68 private hasTags(file
: string): boolean {
69 return this.tagsCaches
.has(file
);
72 private setTags(file
: string, tags
: string[]) {
73 return this.tagsCaches
.set(file
, tags
);
76 private getTags(file
: string): string[] {
77 return this.tagsCaches
.get(file
);
80 private deleteTags(file
: string): boolean {
81 return this.tagsCaches
.delete(file
);
84 private deleteFSWatcher(file
: string): boolean {
85 this.FSWatchers
.get(file
).close();
86 return this.FSWatchers
.delete(file
);
89 private getAuthorizedTagsFromFile(file
: string): string[] {
90 let authorizedTags
: string[] = [];
93 // Load authorization file
94 authorizedTags
= JSON
.parse(fs
.readFileSync(file
, 'utf8')) as string[];
96 FileUtils
.handleFileException(
98 FileType
.Authorization
,
100 error
as NodeJS
.ErrnoException
104 logger
.info(`${this.logPrefix(file)} No authorization file given`);
106 return authorizedTags
;
109 private logPrefix(file
: string): string {
110 return Utils
.logPrefix(` Authorized tags cache for authorization file '${file}' |`);