mirror of
https://github.com/Tria-plc/emaui.git
synced 2026-08-27 15:30:57 +00:00
Adding more functionalities for all the license types
This commit is contained in:
43
libs/api/src/lib/base-api/download.ts
Normal file
43
libs/api/src/lib/base-api/download.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { resolveTokenFromStorage } from '../session';
|
||||
import { BASE_API_URL } from './base-query-with-reauth';
|
||||
|
||||
/**
|
||||
* Opens an authenticated binary endpoint (a rendered PDF) in a new tab.
|
||||
*
|
||||
* RTK Query is not used here: `fetchBaseQuery` parses responses as JSON, and
|
||||
* a plain `window.open` sends no Authorization header, so a guarded document
|
||||
* endpoint would answer 401. Fetching to a blob keeps the bearer token on the
|
||||
* request and still gives the browser something it can display.
|
||||
*/
|
||||
export async function openAuthedDocument(
|
||||
path: string,
|
||||
fallbackName = 'document.pdf',
|
||||
): Promise<void> {
|
||||
const token = resolveTokenFromStorage();
|
||||
const response = await fetch(`${BASE_API_URL}${path}`, {
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
||||
});
|
||||
if (!response.ok) {
|
||||
// The body carries the API's error key, which callers surface verbatim.
|
||||
let message = `${response.status}`;
|
||||
try {
|
||||
const body = await response.json();
|
||||
message = body?.message ?? message;
|
||||
} catch {
|
||||
/* non-JSON error body — the status is all we have */
|
||||
}
|
||||
throw new Error(message);
|
||||
}
|
||||
const blob = await response.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const opened = window.open(url, '_blank', 'noopener');
|
||||
if (!opened) {
|
||||
// Pop-up blocked: fall back to a direct download so the click still works.
|
||||
const anchor = document.createElement('a');
|
||||
anchor.href = url;
|
||||
anchor.download = fallbackName;
|
||||
anchor.click();
|
||||
}
|
||||
// Revoking immediately would race the new tab's load.
|
||||
setTimeout(() => URL.revokeObjectURL(url), 60_000);
|
||||
}
|
||||
Reference in New Issue
Block a user