1 import fs from
'node:fs';
3 import { FileType
} from
'../types';
4 import { FileUtils
, Utils
, logger
} from
'../utils';
6 type TagsCacheValueType
= {
8 tagsFileWatcher
: fs
.FSWatcher
| undefined;
11 export class AuthorizedTagsCache
{
12 private static instance
: AuthorizedTagsCache
| null = null;
13 private readonly tagsCaches
: Map
<string, TagsCacheValueType
>;
15 private constructor() {
16 this.tagsCaches
= new Map
<string, TagsCacheValueType
>();
19 public static getInstance(): AuthorizedTagsCache
{
20 if (AuthorizedTagsCache
.instance
=== null) {
21 AuthorizedTagsCache
.instance
= new AuthorizedTagsCache();
23 return AuthorizedTagsCache
.instance
;
26 public getAuthorizedTags(file
: string): string[] | undefined {
27 if (this.hasTags(file
) === false) {
28 this.setTags(file
, this.getAuthorizedTagsFromFile(file
));
30 return this.getTags(file
);
33 public deleteAuthorizedTags(file
: string): boolean {
34 return this.deleteTags(file
);
37 private hasTags(file
: string): boolean {
38 return this.tagsCaches
.has(file
);
41 private setTags(file
: string, tags
: string[]) {
42 return this.tagsCaches
.set(file
, {
44 tagsFileWatcher
: FileUtils
.watchJsonFile(
46 FileType
.Authorization
,
49 (event
, filename
) => {
50 if (Utils
.isNotEmptyString(filename
) && event
=== 'change') {
53 `${this.logPrefix(file)} ${FileType.Authorization} file have changed, reload`
55 this.deleteTags(file
);
57 FileUtils
.handleFileException(
59 FileType
.Authorization
,
60 error
as NodeJS
.ErrnoException
,
73 private getTags(file
: string): string[] | undefined {
74 return this.tagsCaches
.get(file
)?.tags
;
77 private deleteTags(file
: string): boolean {
78 this.tagsCaches
.get(file
)?.tagsFileWatcher
?.close();
79 return this.tagsCaches
.delete(file
);
82 private getAuthorizedTagsFromFile(file
: string): string[] {
83 let authorizedTags
: string[] = [];
86 // Load authorization file
87 authorizedTags
= JSON
.parse(fs
.readFileSync(file
, 'utf8')) as string[];
89 FileUtils
.handleFileException(
91 FileType
.Authorization
,
92 error
as NodeJS
.ErrnoException
,
97 logger
.info(`${this.logPrefix(file)} No authorization file given`);
99 return authorizedTags
;
102 private logPrefix
= (file
: string): string => {
103 return Utils
.logPrefix(` Authorized tags cache for authorization file '${file}' |`);