UNPKG

@oxyhq/services

Version:

Reusable OxyHQ module to handle authentication, user management, karma system, device-based session management and more 🚀

103 lines (101 loc) • 3.19 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useFileDownloadUrl = exports.setOxyFileUrlInstance = void 0; var _react = require("react"); let oxyInstance = null; const setOxyFileUrlInstance = instance => { oxyInstance = instance; }; exports.setOxyFileUrlInstance = setOxyFileUrlInstance; /** * Hook to resolve a file's download URL asynchronously. * * Prefers `getFileDownloadUrlAsync` and falls back to the synchronous * `getFileDownloadUrl` helper if the async call fails. */ const useFileDownloadUrl = (fileId, options) => { const [url, setUrl] = (0, _react.useState)(null); const [loading, setLoading] = (0, _react.useState)(false); const [error, setError] = (0, _react.useState)(null); (0, _react.useEffect)(() => { if (!fileId) { setUrl(null); setLoading(false); setError(null); return; } if (!oxyInstance) { // Fail silently but don't crash the UI – caller can decide what to do with null URL. setUrl(null); setLoading(false); setError(new Error('OxyServices instance not configured for useFileDownloadUrl')); return; } let cancelled = false; const load = async () => { setLoading(true); setError(null); // Store instance in local variable for TypeScript null checking const instance = oxyInstance; if (!instance) { setLoading(false); setError(new Error('OxyServices instance not configured for useFileDownloadUrl')); return; } try { const { variant, expiresIn } = options || {}; let resolvedUrl = null; if (typeof instance.getFileDownloadUrlAsync === 'function') { resolvedUrl = await instance.getFileDownloadUrlAsync(fileId, variant, expiresIn); } if (!resolvedUrl && typeof instance.getFileDownloadUrl === 'function') { resolvedUrl = instance.getFileDownloadUrl(fileId, variant, expiresIn); } if (!cancelled) { setUrl(resolvedUrl || null); } } catch (err) { // Fallback to sync URL on error where possible try { if (typeof instance.getFileDownloadUrl === 'function') { const { variant, expiresIn } = options || {}; const fallbackUrl = instance.getFileDownloadUrl(fileId, variant, expiresIn); if (!cancelled) { setUrl(fallbackUrl || null); setError(err instanceof Error ? err : new Error(String(err))); } return; } } catch { // ignore secondary failure, we'll surface the original error below } if (!cancelled) { setError(err instanceof Error ? err : new Error(String(err))); } } finally { if (!cancelled) { setLoading(false); } } }; load(); return () => { cancelled = true; }; }, [fileId, options?.variant, options?.expiresIn]); return { url, loading, error }; }; exports.useFileDownloadUrl = useFileDownloadUrl; //# sourceMappingURL=useFileDownloadUrl.js.map