photo.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import { ref, getDownloadURL, listAll } from "firebase/storage";
  2. import { storage } from "../firebase";
  3. // Cache for URL storage
  4. const urlCache = new Map<string, { url: string; timestamp: number }>();
  5. const CACHE_DURATION = 1000 * 60 * 60; // 1 hour
  6. export async function getPhotoUrl(filePath: string): Promise<string> {
  7. // Check cache first
  8. const cached = urlCache.get(filePath);
  9. const now = Date.now();
  10. if (cached && now - cached.timestamp < CACHE_DURATION) {
  11. return cached.url;
  12. }
  13. const storageRef = ref(storage, filePath);
  14. try {
  15. const url = await getDownloadURL(storageRef);
  16. // Store in cache
  17. urlCache.set(filePath, { url, timestamp: now });
  18. return url;
  19. } catch (error) {
  20. throw error;
  21. }
  22. }
  23. // Batch fetch URLs
  24. export async function batchGetPhotoUrls(
  25. filePaths: string[],
  26. ): Promise<Record<string, string>> {
  27. const results: Record<string, string> = {};
  28. const fetchNeeded: string[] = [];
  29. // Check cache first
  30. const now = Date.now();
  31. filePaths.forEach((path) => {
  32. const cached = urlCache.get(path);
  33. if (cached && now - cached.timestamp < CACHE_DURATION) {
  34. results[path] = cached.url;
  35. } else {
  36. fetchNeeded.push(path);
  37. }
  38. });
  39. if (fetchNeeded.length > 0) {
  40. // Fetch all needed URLs in parallel
  41. const promises = fetchNeeded.map(async (path) => {
  42. const url = await getPhotoUrl(path);
  43. results[path] = url;
  44. });
  45. await Promise.all(promises);
  46. }
  47. return results;
  48. }
  49. export async function listPhotos(folderPath: string): Promise<string[]> {
  50. const cacheKey = `folder_${folderPath}`;
  51. const cached = urlCache.get(cacheKey);
  52. const now = Date.now();
  53. if (cached && now - cached.timestamp < CACHE_DURATION) {
  54. return JSON.parse(cached.url); // In this case, url contains JSON string of URLs array
  55. }
  56. const folderRef = ref(storage, folderPath);
  57. try {
  58. const res = await listAll(folderRef);
  59. const urls = await Promise.all(
  60. res.items.map((itemRef) => getDownloadURL(itemRef)),
  61. );
  62. // Cache the results
  63. urlCache.set(cacheKey, {
  64. url: JSON.stringify(urls),
  65. timestamp: now,
  66. });
  67. return urls;
  68. } catch (error) {
  69. throw error;
  70. }
  71. }