From 67b314b507d0f71c9a902b261199bf656c639373 Mon Sep 17 00:00:00 2001 From: ztimson Date: Sun, 21 Apr 2024 21:03:07 -0400 Subject: [PATCH] Added download function using fetch and links --- package.json | 2 +- src/xhr.ts | 22 ++++++++++++++++++++-- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index c7ae5c8..207cf92 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@ztimson/utils", - "version": "0.4.1", + "version": "0.5.0", "description": "Utility library", "author": "Zak Timson", "license": "MIT", diff --git a/src/xhr.ts b/src/xhr.ts index 4d1f58f..d70d83c 100644 --- a/src/xhr.ts +++ b/src/xhr.ts @@ -7,6 +7,7 @@ export type RequestOptions = { method?: 'GET' | 'POST' | 'PATCH' | 'DELETE'; body?: any; headers?: {[key: string | symbol]: string | null | undefined}; + skipConverting?: boolean; [key: string]: any; } @@ -44,6 +45,14 @@ export class XHR { return () => { this.interceptors[key] = null; } } + download(opts: RequestOptions & {url: string}) { + this.request({...opts, skipConverting: true}).then(async resp => { + const blob = await resp.blob(); + download(URL.createObjectURL(blob), opts.url.split('/').pop()); + URL.revokeObjectURL(opts.url); + }); + } + async request(opts: RequestOptions = {}): Promise { 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'); @@ -67,9 +76,18 @@ export class XHR { } if(!resp.ok) throw new Error(resp.statusText); - if(resp.headers.get('Content-Type')?.startsWith('application/json')) return await resp.json(); - if(resp.headers.get('Content-Type')?.startsWith('text/plain')) return await resp.text(); + if(!opts.skipConverting && resp.headers.get('Content-Type')?.startsWith('application/json')) return await resp.json(); + if(!opts.skipConverting && resp.headers.get('Content-Type')?.startsWith('text/plain')) return await resp.text(); 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); +}