Compare commits

...

11 Commits

Author SHA1 Message Date
948fba3a2c Allow disabling response decoding
All checks were successful
Build / Build NPM Project (push) Successful in 49s
Build / Tag Version (push) Successful in 8s
2024-08-13 14:48:48 -04:00
a168b03caf Renamed entry point to index
All checks were successful
Build / Build NPM Project (push) Successful in 47s
Build / Tag Version (push) Successful in 7s
2024-08-09 12:27:44 -04:00
75160b7dbc Fixed upload headers
All checks were successful
Build / Build NPM Project (push) Successful in 22s
Build / Tag Version (push) Successful in 4s
2024-07-19 10:16:31 -04:00
af887a0bfb Fixed http body
All checks were successful
Build / Build NPM Project (push) Successful in 22s
Build / Tag Version (push) Successful in 4s
2024-07-19 10:05:47 -04:00
7626c20f08 Improved http
All checks were successful
Build / Build NPM Project (push) Successful in 22s
Build / Tag Version (push) Successful in 5s
2024-07-19 09:24:53 -04:00
6998616445 Fixed import
All checks were successful
Build / Build NPM Project (push) Successful in 22s
Build / Tag Version (push) Successful in 4s
2024-07-19 09:02:42 -04:00
627757ff6d Added generics to upload function
All checks were successful
Build / Build NPM Project (push) Successful in 22s
Build / Tag Version (push) Successful in 4s
2024-07-19 08:59:15 -04:00
0a775f919b Added filebrowser & Merged a bunch of functions into file utilities
All checks were successful
Build / Build NPM Project (push) Successful in 23s
Build / Tag Version (push) Successful in 4s
2024-07-19 08:45:33 -04:00
7063b80bdd Added download blob function
All checks were successful
Build / Build NPM Project (push) Successful in 22s
Build / Tag Version (push) Successful in 5s
2024-07-19 08:33:26 -04:00
f3049160b6 Fixed imports
All checks were successful
Build / Build NPM Project (push) Successful in 21s
Build / Tag Version (push) Successful in 4s
2024-07-19 00:26:30 -04:00
e21273ddb2 Fixed exports
All checks were successful
Build / Build NPM Project (push) Successful in 21s
Build / Tag Version (push) Successful in 4s
2024-07-19 00:22:00 -04:00
7 changed files with 87 additions and 68 deletions

View File

@ -1,6 +1,6 @@
{
"name": "@ztimson/utils",
"version": "0.13.0",
"version": "0.14.7",
"description": "Utility library",
"author": "Zak Timson",
"license": "MIT",
@ -9,13 +9,13 @@
"type": "git",
"url": "https://git.zakscode.com/ztimson/js-utilities"
},
"main": "./dist/utils.cjs",
"module": "./dist/utils.mjs",
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
".": {
"import": "./dist/utils.mjs",
"require": "./dist/utils.cjs",
"import": "./dist/index.mjs",
"require": "./dist/index.cjs",
"types": "./dist/index.d.ts"
}
},

View File

@ -1,8 +0,0 @@
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);
}

54
src/files.ts Normal file
View File

@ -0,0 +1,54 @@
import {PromiseProgress} from './promise-progress';
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);
}
export function downloadBlob(blob: Blob, name: string) {
const url = URL.createObjectURL(blob);
download(url, name);
URL.revokeObjectURL(url);
}
export function fileBrowser(options: {accept?: string, multiple?: boolean} = {}): Promise<File[]> {
return new Promise(res => {
const input = document.createElement('input');
input.type = 'file';
input.accept = options.accept || '*';
input.style.display='none';
input.multiple = !!options.multiple;
input.onblur = input.onchange = async () => {
res(Array.from(<any>input.files));
input.remove();
}
document.body.appendChild(input);
input.click();
});
}
export function uploadWithProgress<T>(options: {
url: string;
files: File[];
headers?: {[key: string]: string};
withCredentials?: boolean;
}): PromiseProgress<T> {
return new PromiseProgress<T>((res, rej, prog) => {
const xhr = new XMLHttpRequest();
const formData = new FormData();
options.files.forEach(f => formData.append('file', f));
xhr.withCredentials = !!options.withCredentials
xhr.upload.addEventListener('progress', (event) => event.lengthComputable ? prog(event.loaded / event.total) : null);
xhr.upload.addEventListener('load', (resp) => res(<any>resp));
xhr.upload.addEventListener('error', (err) => rej(err));
xhr.open('POST', options.url);
Object.entries(options.headers || {}).forEach(([key, value]) => xhr.setRequestHeader(key, value));
xhr.send(formData);
});
}

View File

@ -1,17 +1,18 @@
import {clean} from './objects';
import {PromiseProgress} from './promise-progress.ts';
import {PromiseProgress} from './promise-progress';
export type DecodedResponse<T> = Response & {data?: T}
export type DecodedResponse<T> = Response & {data: T | null}
export type HttpInterceptor = (response: Response, next: () => void) => void;
export type HttpRequestOptions = {
url?: string;
fragment?: string;
query?: {key: string, value: string}[] | {[key: string]: string};
method?: 'GET' | 'POST' | 'PATCH' | 'DELETE';
body?: any;
decode?: boolean;
fragment?: string;
headers?: {[key: string | symbol]: string | null | undefined};
method?: 'GET' | 'POST' | 'PATCH' | 'DELETE';
query?: {key: string, value: string}[] | {[key: string]: string};
url?: string;
[key: string]: any;
}
@ -70,7 +71,7 @@ export class Http {
});
if(typeof opts.body == 'object' && opts.body != null && headers['Content-Type'] == 'application/json')
opts.body = JSON.stringify(opts.json);
opts.body = JSON.stringify(opts.body);
// Send request
return new PromiseProgress((res, rej, prog) => {
@ -78,14 +79,11 @@ export class Http {
headers,
method: opts.method || (opts.body ? 'POST' : 'GET'),
body: opts.body
}).then(async (resp: DecodedResponse<T>) => {
console.log('done!');
}).then(async (resp: any) => {
for(let fn of [...Object.values(Http.interceptors), ...Object.values(this.interceptors)]) {
await new Promise<void>(res => fn(resp, () => res()));
}
if(!resp.ok) rej(resp);
const contentLength = resp.headers.get('Content-Length');
const total = contentLength ? parseInt(contentLength, 10) : 0;
let loaded = 0;
@ -94,28 +92,29 @@ export class Http {
const stream = new ReadableStream({
start(controller) {
function push() {
reader?.read().then(({done, value}) => {
if(done) return controller.close();
loaded += value.byteLength;
reader?.read().then((event: any) => {
if(event.done) return controller.close();
loaded += event.value.byteLength;
prog(loaded / total);
controller.enqueue(value);
controller.enqueue(event.value);
push();
}).catch(error => {
controller.error(error);
});
}).catch((error: any) => controller.error(error));
}
push();
}
});
const data = new Response(stream);
resp.data = new Response(stream);
if(opts.decode !== false) {
const content = resp.headers.get('Content-Type')?.toLowerCase();
if(content?.includes('json')) resp.data = <T>await data.json();
else if(content?.includes('text')) resp.data = <T>await data.text();
else if(content?.includes('form')) resp.data = <T>await data.formData();
else if(content?.includes('application')) resp.data = <T>await data.blob();
res(resp);
if(content?.includes('json')) resp.data = <T>await resp.data.json();
else if(content?.includes('text')) resp.data = <T>await resp.data.text();
else if(content?.includes('form')) resp.data = <T>await resp.data.formData();
else if(content?.includes('application')) resp.data = <T>await resp.data.blob();
}
if(resp.ok) res(resp);
else rej(resp);
})
});
}

View File

@ -1,9 +1,9 @@
export * from './array';
export * from './aset';
export * from './download';
export * from './files';
export * from './emitter';
export * from './errors';
export * from './http.ts';
export * from './http';
export * from './logger';
export * from './math';
export * from './misc';
@ -11,4 +11,3 @@ export * from './objects';
export * from './promise-progress';
export * from './string';
export * from './time';
export * from './upload.ts';

View File

@ -1,25 +0,0 @@
import {PromiseProgress} from './promise-progress.ts';
export type UploadOptions = {
url: string;
file: File;
headers?: {[key: string]: string};
withCredentials?: boolean;
}
export function uploadWithProgress(options: UploadOptions) {
return new PromiseProgress((res, rej, prog) => {
const xhr = new XMLHttpRequest();
const formData = new FormData();
formData.append('file', options.file);
xhr.withCredentials = !!options.withCredentials
Object.entries(options.headers || {}).forEach(([key, value]) => xhr.setRequestHeader(key, value));
xhr.upload.addEventListener('progress', (event) => event.lengthComputable ? prog(event.loaded / event.total) : null);
xhr.upload.addEventListener('load', (resp) => res(resp));
xhr.upload.addEventListener('error', (err) => rej(err));
xhr.open('POST', options.url);
xhr.send(formData);
});
}

View File

@ -8,8 +8,8 @@ export default defineConfig({
entry: resolve(process.cwd(), 'src/index.ts'),
name: 'utils',
fileName: (module, entryName) => {
if(module == 'es') return 'utils.mjs';
if(module == 'umd') return 'utils.cjs';
if(module == 'es') return 'index.mjs';
if(module == 'umd') return 'index.cjs';
}
},
emptyOutDir: true,