| 130 | } |
| 131 | |
| 132 | class Cache { |
| 133 | static cacheDirectory = relativePath('cache'); |
| 134 | static REFRESH = 'REFRESH'; |
| 135 | |
| 136 | static setCacheDirectory(folder: string): void { |
| 137 | // replaces end '/' |
| 138 | Cache.cacheDirectory = folder.replace(/\/$/, '') + '/'; |
| 139 | } |
| 140 | |
| 141 | static put(func: Function | string, keyData: any, data: any): void { |
| 142 | _createCacheDirectoryIfNotExists(func); |
| 143 | const path = _getCachePath(func, keyData); |
| 144 | writeJson(data, path); |
| 145 | } |
| 146 | |
| 147 | static hash(data: any): string { |
| 148 | return _hash(data); |
| 149 | } |
| 150 | |
| 151 | static has(func: Function | string, keyData: any): boolean { |
| 152 | _createCacheDirectoryIfNotExists(func); |
| 153 | const path = _getCachePath(func, keyData); |
| 154 | return _has(path); |
| 155 | } |
| 156 | |
| 157 | static get(func: Function | string, keyData: any, raiseException = true): any { |
| 158 | if (Array.isArray(keyData)) { |
| 159 | return Cache.getItems(func, keyData); |
| 160 | } |
| 161 | |
| 162 | _createCacheDirectoryIfNotExists(func); |
| 163 | const path = _getCachePath(func, keyData); |
| 164 | if (_has(path)) { |
| 165 | try { |
| 166 | return _get(path); |
| 167 | } catch (error) { |
| 168 | return null; |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | if (raiseException) { |
| 173 | throw new CacheMissException(path); |
| 174 | } |
| 175 | return null; |
| 176 | } |
| 177 | |
| 178 | static getItems(func: Function | string, items?: any[]): any[] { |
| 179 | if (typeof items === 'string') { |
| 180 | return Cache.getItems(func, [items]); |
| 181 | } |
| 182 | |
| 183 | const hashes = Cache.getItemsHashes(func, items); |
| 184 | const fnName = getFnName(func); |
| 185 | const paths = hashes.map(r => path.join(Cache.cacheDirectory, fnName, `${r}.json`)); |
| 186 | return _readJsonFiles(paths); |
| 187 | } |
| 188 | |
| 189 | static getItemsHashes(func: Function | string, items?: any[]): string[] { |
nothing calls this directly
no test coverage detected