Added download function using fetch and links
All checks were successful
Build / Build NPM Project (push) Successful in 37s
Build / Tag Version (push) Successful in 7s
Build / Publish (push) Successful in 16s

This commit is contained in:
Zakary Timson 2024-04-21 21:03:07 -04:00
parent f5d66f0d8f
commit 67b314b507
2 changed files with 21 additions and 3 deletions

View File

@ -1,6 +1,6 @@
{ {
"name": "@ztimson/utils", "name": "@ztimson/utils",
"version": "0.4.1", "version": "0.5.0",
"description": "Utility library", "description": "Utility library",
"author": "Zak Timson", "author": "Zak Timson",
"license": "MIT", "license": "MIT",

View File

@ -7,6 +7,7 @@ export type RequestOptions = {
method?: 'GET' | 'POST' | 'PATCH' | 'DELETE'; method?: 'GET' | 'POST' | 'PATCH' | 'DELETE';
body?: any; body?: any;
headers?: {[key: string | symbol]: string | null | undefined}; headers?: {[key: string | symbol]: string | null | undefined};
skipConverting?: boolean;
[key: string]: any; [key: string]: any;
} }
@ -44,6 +45,14 @@ export class XHR {
return () => { this.interceptors[key] = <any>null; } return () => { this.interceptors[key] = <any>null; }
} }
download(opts: RequestOptions & {url: string}) {
this.request<Response>({...opts, skipConverting: true}).then(async resp => {
const blob = await resp.blob();
download(URL.createObjectURL(blob), <string>opts.url.split('/').pop());
URL.revokeObjectURL(opts.url);
});
}
async request<T>(opts: RequestOptions = {}): Promise<T> { async request<T>(opts: RequestOptions = {}): Promise<T> {
if(!this.opts.url && !opts.url) throw new Error('URL needs to be set'); if(!this.opts.url && !opts.url) throw new Error('URL needs to be set');
const url = (opts.url?.startsWith('http') ? opts.url : (this.opts.url || '') + (opts.url || '')).replace(/([^:]\/)\/+/g, '$1'); const url = (opts.url?.startsWith('http') ? opts.url : (this.opts.url || '') + (opts.url || '')).replace(/([^:]\/)\/+/g, '$1');
@ -67,9 +76,18 @@ export class XHR {
} }
if(!resp.ok) throw new Error(resp.statusText); if(!resp.ok) throw new Error(resp.statusText);
if(resp.headers.get('Content-Type')?.startsWith('application/json')) return await resp.json(); if(!opts.skipConverting && resp.headers.get('Content-Type')?.startsWith('application/json')) return await resp.json();
if(resp.headers.get('Content-Type')?.startsWith('text/plain')) return await <any>resp.text(); if(!opts.skipConverting && resp.headers.get('Content-Type')?.startsWith('text/plain')) return await <any>resp.text();
return resp; return resp;
}); });
} }
} }
export function download(href: any, name: string) {
const a = document.createElement('a');
a.href = href;
a.download = name;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}