Compare commits
16 Commits
Author | SHA1 | Date | |
---|---|---|---|
6d13df39f5 | |||
2d63db0ebb | |||
535fc0271e | |||
d587b92ea4 | |||
26c6084052 | |||
874bba59d3 | |||
948fba3a2c | |||
a168b03caf | |||
75160b7dbc | |||
af887a0bfb | |||
7626c20f08 | |||
6998616445 | |||
627757ff6d | |||
0a775f919b | |||
7063b80bdd | |||
f3049160b6 |
10
package.json
10
package.json
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ztimson/utils",
|
||||
"version": "0.13.1",
|
||||
"version": "0.15.0",
|
||||
"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"
|
||||
}
|
||||
},
|
||||
|
@ -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);
|
||||
}
|
56
src/files.ts
Normal file
56
src/files.ts
Normal file
@ -0,0 +1,56 @@
|
||||
import {deepCopy, JSONAttemptParse} from './objects.ts';
|
||||
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.addEventListener('loadend', () => res(<T>JSONAttemptParse(xhr.responseText)));
|
||||
xhr.addEventListener('error', () => rej(JSONAttemptParse(xhr.responseText)));
|
||||
xhr.addEventListener('timeout', () => rej({error: 'Request timed out'}));
|
||||
|
||||
xhr.open('POST', options.url);
|
||||
Object.entries(options.headers || {}).forEach(([key, value]) => xhr.setRequestHeader(key, value));
|
||||
xhr.send(formData);
|
||||
});
|
||||
}
|
49
src/http.ts
49
src/http.ts
@ -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 == null || opts.decode) {
|
||||
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('form')) resp.data = <T>await resp.data.formData();
|
||||
else 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('application')) resp.data = <T>await resp.data.blob();
|
||||
}
|
||||
|
||||
if(resp.ok) res(resp);
|
||||
else rej(resp);
|
||||
})
|
||||
});
|
||||
}
|
||||
|
@ -1,6 +1,6 @@
|
||||
export * from './array';
|
||||
export * from './aset';
|
||||
export * from './download';
|
||||
export * from './files';
|
||||
export * from './emitter';
|
||||
export * from './errors';
|
||||
export * from './http';
|
||||
@ -11,4 +11,3 @@ export * from './objects';
|
||||
export * from './promise-progress';
|
||||
export * from './string';
|
||||
export * from './time';
|
||||
export * from './upload';
|
||||
|
12
src/misc.ts
12
src/misc.ts
@ -1,17 +1,5 @@
|
||||
import {md5} from './string';
|
||||
|
||||
/**
|
||||
* Convert data into a form encoded format.
|
||||
*
|
||||
* @param {any} data - data to convert
|
||||
* @returns {string} - Ecodeded form data
|
||||
*/
|
||||
export function formEncode(data: any): string {
|
||||
return Object.entries(data).map(([key, value]) =>
|
||||
encodeURIComponent(key) + '=' + encodeURIComponent(<any>value)
|
||||
).join('&');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get profile image from Gravatar
|
||||
*
|
||||
|
@ -119,6 +119,17 @@ export function flattenObj(obj: any, parent?: any, result: any = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert object to FormData
|
||||
* @param target - Object to convert
|
||||
* @return {FormData} - Form object
|
||||
*/
|
||||
export function formData(target: any): FormData {
|
||||
const data = new FormData();
|
||||
Object.entries(target).forEach(([key, value]) => data.append(key, <any>value));
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that an object has the following values
|
||||
*
|
||||
@ -175,7 +186,12 @@ export function mixin(target: any, constructors: any[]) {
|
||||
});
|
||||
}
|
||||
|
||||
export function sanitizedJSON(obj: any, space?: number) {
|
||||
export function JSONAttemptParse<T>(json: string): T | string {
|
||||
try { return JSON.parse(json); }
|
||||
catch { return json; }
|
||||
}
|
||||
|
||||
export function JSONSanitized(obj: any, space?: number) {
|
||||
let cache: any[] = [];
|
||||
return JSON.parse(JSON.stringify(obj, (key, value) => {
|
||||
if (typeof value === 'object' && value !== null) {
|
||||
@ -185,3 +201,15 @@ export function sanitizedJSON(obj: any, space?: number) {
|
||||
return value;
|
||||
}, space));
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert object into URL encoded string
|
||||
*
|
||||
* @param {any} data - data to convert
|
||||
* @returns {string} - Encoded form data
|
||||
*/
|
||||
export function urlEncode(data: any): string {
|
||||
return Object.entries(data).map(([key, value]) =>
|
||||
encodeURIComponent(key) + '=' + encodeURIComponent(<any>value)
|
||||
).join('&');
|
||||
}
|
||||
|
@ -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);
|
||||
});
|
||||
}
|
@ -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,
|
||||
|
Reference in New Issue
Block a user