1 import fs from
'node:fs';
3 import { FileType
} from
'../types';
4 import { FileUtils
, Utils
, logger
} from
'../utils';
6 export class AuthorizedTagsCache
{
7 private static instance
: AuthorizedTagsCache
| null = null;
8 private readonly tagsCaches
: Map
<string, string[]>;
9 private readonly FSWatchers
: Map
<string, fs
.FSWatcher
| undefined>;
11 private constructor() {
12 this.tagsCaches
= new Map
<string, string[]>();
13 this.FSWatchers
= new Map
<string, fs
.FSWatcher
| undefined>();
16 public static getInstance(): AuthorizedTagsCache
{
17 if (AuthorizedTagsCache
.instance
=== null) {
18 AuthorizedTagsCache
.instance
= new AuthorizedTagsCache();
20 return AuthorizedTagsCache
.instance
;
23 public getAuthorizedTags(file
: string): string[] | undefined {
24 if (this.hasTags(file
) === false) {
25 this.setTags(file
, this.getAuthorizedTagsFromFile(file
));
26 // Monitor authorization file
27 this.FSWatchers
.has(file
) === false &&
30 FileUtils
.watchJsonFile(
32 FileType
.Authorization
,
35 (event
, filename
) => {
36 if (Utils
.isNotEmptyString(filename
) && event
=== 'change') {
39 `${this.logPrefix(file)} ${FileType.Authorization} file have changed, reload`
41 this.deleteTags(file
);
42 this.deleteFSWatcher(file
);
44 FileUtils
.handleFileException(
46 FileType
.Authorization
,
47 error
as NodeJS
.ErrnoException
,
59 return this.getTags(file
);
62 public deleteAuthorizedTags(file
: string): boolean {
63 return this.deleteTags(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[] | undefined {
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
,
97 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}' |`);