diff --git a/lib/cache.js b/lib/cache.js index 36a5f95..2b5db21 100644 --- a/lib/cache.js +++ b/lib/cache.js @@ -526,6 +526,55 @@ class VInfoCache { } return caches; } + + /** + * Deletes the stored cache for a given video ID. + * + * The function will delete the cache file for the specified video ID if it exists. + * If you specified the `cacheOptions.cachePath` option, the function will use the provided path + * to locate the cache file. Otherwise, it will use the default cache directory path. + * + * @param {string} id - The video ID to delete the cache for. + * @param {Object} cacheOptions - Options for the cache. + * @param {string} [cacheOptions.cachePath] - The path to the cache directory. Defaults to + * {@link module:cache~VINFO_CACHE_PATH `VINFO_CACHE_PATH`}. + * @returns {Promise.} A promise that resolves to `true` if the cache is deleted successfully, + * or `false` if the cache does not exist. + * + * @throws {InvalidTypeError} If the given cache options is not a plain object. + * + * @static + * @async + * @method + * @package + * @since 2.0.0 + */ + static async deleteCache(id, cacheOptions) { + validateId(id); // Validate the video ID + + if (!TypeUtils.isPlainObject(cacheOptions)) { + throw new InvalidTypeError('Cache options type is invalid', { + actualType: TypeUtils.getType(cacheOptions), + expectedType: TypeUtils.getType({}) + }); + } + + cacheOptions.cachePath = cacheOptions.cachePath || VINFO_CACHE_PATH; + const cachePath = typeof cacheOptions.cachePath === 'string' + ? path.join(cacheOptions.cachePath, id) + : getCachePath(id); + + // Remove the cache file only if exists + try { + await fs.promises.access(cachePath, fs.constants.F_OK); + await fs.promises.unlink(cachePath); + // eslint-disable-next-line no-unused-vars + } catch (_) { + return false; + } + + return true; + } }