helpers.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { logError } from "@ente/shared/sentry";
  2. import { CacheStorageService } from ".";
  3. import { CACHES } from "./constants";
  4. import { LimitedCache } from "./types";
  5. export async function cached(
  6. cacheName: string,
  7. id: string,
  8. get: () => Promise<Blob>,
  9. ): Promise<Blob> {
  10. const cache = await CacheStorageService.open(cacheName);
  11. const cacheResponse = await cache.match(id);
  12. let result: Blob;
  13. if (cacheResponse) {
  14. result = await cacheResponse.blob();
  15. } else {
  16. result = await get();
  17. try {
  18. await cache.put(id, new Response(result));
  19. } catch (e) {
  20. // TODO: handle storage full exception.
  21. console.error("Error while storing file to cache: ", id);
  22. }
  23. }
  24. return result;
  25. }
  26. let thumbCache: LimitedCache;
  27. export async function getBlobFromCache(
  28. cacheName: string,
  29. url: string,
  30. ): Promise<Blob> {
  31. if (!thumbCache) {
  32. thumbCache = await CacheStorageService.open(cacheName);
  33. }
  34. const response = await thumbCache.match(url);
  35. if (!response) {
  36. return undefined;
  37. }
  38. return response.blob();
  39. }
  40. export async function deleteAllCache() {
  41. try {
  42. await CacheStorageService.delete(CACHES.THUMBS);
  43. await CacheStorageService.delete(CACHES.FACE_CROPS);
  44. await CacheStorageService.delete(CACHES.FILES);
  45. } catch (e) {
  46. logError(e, "deleteAllCache failed"); // log and ignore
  47. }
  48. }