Compare commits

...

7 Commits

Author SHA1 Message Date
3ca956e531 Fixed fetch errors
All checks were successful
Build / Build NPM Project (push) Successful in 1m27s
Build / Tag Version (push) Successful in 18s
Build / Publish (push) Successful in 26s
2024-05-31 10:04:51 -04:00
9350c837e5 Added math functions
All checks were successful
Build / Build NPM Project (push) Successful in 1m29s
Build / Tag Version (push) Successful in 19s
Build / Publish (push) Successful in 26s
2024-05-27 13:51:41 -04:00
86196c3feb Added promise progress
All checks were successful
Build / Build NPM Project (push) Successful in 17s
Build / Tag Version (push) Successful in 4s
Build / Publish (push) Successful in 7s
2024-04-27 23:09:12 -04:00
0985ff145e Fixed file upload types
All checks were successful
Build / Build NPM Project (push) Successful in 16s
Build / Tag Version (push) Successful in 4s
Build / Publish (push) Successful in 7s
2024-04-24 07:06:17 -04:00
7cd717fc7d Fixed upload export
All checks were successful
Build / Build NPM Project (push) Successful in 15s
Build / Tag Version (push) Successful in 5s
Build / Publish (push) Successful in 7s
2024-04-24 07:01:36 -04:00
2fe8cdb96a Added upload function which tracks progress
All checks were successful
Build / Build NPM Project (push) Successful in 16s
Build / Tag Version (push) Successful in 4s
Build / Publish (push) Successful in 7s
2024-04-24 06:57:15 -04:00
34c2df7a1a Fixed import
All checks were successful
Build / Build NPM Project (push) Successful in 16s
Build / Tag Version (push) Successful in 4s
Build / Publish (push) Successful in 7s
2024-04-23 09:09:07 -04:00
7 changed files with 93 additions and 58 deletions

View File

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

View File

@ -1,10 +1,3 @@
import {TypedEmitter, TypedEvents} from './emitter.ts';
export type downloadEvents = TypedEvents & {
complete: (blob: Blob) => any;
progress: (progress: number) => any;
}
export function download(href: any, name: string) { export function download(href: any, name: string) {
const a = document.createElement('a'); const a = document.createElement('a');
a.href = href; a.href = href;
@ -13,40 +6,3 @@ export function download(href: any, name: string) {
a.click(); a.click();
document.body.removeChild(a); document.body.removeChild(a);
} }
/**
* Download a URL using fetch so progress can be tracked. Uses Typed Emitter to emit a "progress" &
* "complete" event.
*
* @param {string} url
* @param {string} downloadName
* @return {TypedEmitter<downloadEvents>}
*/
export function downloadProgress(url: string, downloadName?: string) {
const emitter = new TypedEmitter<downloadEvents>();
fetch(url).then(response => {
const contentLength = response.headers.get('Content-Length') || '0';
const total = parseInt(contentLength, 10);
let chunks: any[] = [], loaded = 0;
const reader = response.body?.getReader();
reader?.read().then(function processResult(result) {
if(result.done) {
const blob = new Blob(chunks);
if(downloadName) {
const url = URL.createObjectURL(blob);
download(url, downloadName);
URL.revokeObjectURL(url);
}
emitter.emit('complete', blob);
} else {
const chunk = result.value;
chunks.push(chunk);
loaded += chunk.length;
const progress = loaded / total;
emitter.emit('progress', progress);
reader.read().then(processResult);
}
});
});
return emitter;
}

View File

@ -1,15 +1,3 @@
import {XHR} from './xhr';
XHR.addInterceptor((resp: Response, next: () => void) => {
if(resp.status == 200) return next();
if(resp.status == 400) throw new BadRequestError(resp.statusText);
if(resp.status == 401) throw new UnauthorizedError(resp.statusText);
if(resp.status == 403) throw new ForbiddenError(resp.statusText);
if(resp.status == 404) throw new NotFoundError(resp.statusText);
if(resp.status == 500) throw new InternalServerError(resp.statusText);
throw new CustomError(resp.statusText, resp.status);
});
export class CustomError extends Error { export class CustomError extends Error {
static code = 500; static code = 500;

View File

@ -4,8 +4,10 @@ export * from './download';
export * from './emitter'; export * from './emitter';
export * from './errors'; export * from './errors';
export * from './logger'; export * from './logger';
export * from './math';
export * from './misc'; export * from './misc';
export * from './objects'; export * from './objects';
export * from './promise-progress';
export * from './string'; export * from './string';
export * from './time'; export * from './time';
export * from './xhr'; export * from './xhr';

45
src/math.ts Normal file
View File

@ -0,0 +1,45 @@
/**
* Convert decimal number to fraction
*
* @example
* ```js
* dec2Frac(1.25) // Outputs: "1 1/4"
* ```
*
* @param {number} num Number to convert
* @return {string} Fraction with remainder
*/
export function dec2Frac(num: number) {
const gcd = (a: number, b: number): number => {
if (b < 0.0000001) return a;
return gcd(b, ~~(a % b));
};
const len = num.toString().length - 2;
let denominator = Math.pow(10, len);
let numerator = num * denominator;
const divisor = gcd(numerator, denominator);
numerator = ~~(numerator / divisor);
denominator = ~~(denominator / divisor)
const remainder = ~~(numerator / denominator);
numerator -= remainder * denominator;
return `${remainder ? remainder + ' ' : ''}${~~(numerator)}/${~~(denominator)}`;
}
/**
* Convert fraction to decimal number
*
* @example
* ```js
* fracToDec('1 1/4') // Outputs: 1.25
* ```
*
* @param {string} frac Fraction to convert
* @return {number} Faction as a decimal
*/
export function fracToDec(frac: string) {
let split = frac.split(' ');
const whole = split.length == 2 ? Number(split[0]) : 0;
split = (<string>split.pop()).split('/');
return whole + (Number(split[0]) / Number(split[1]));
}

26
src/promise-progress.ts Normal file
View File

@ -0,0 +1,26 @@
export type ProgressCallback = (progress: number) => any;
export class PromiseProgress<T> extends Promise<T> {
private listeners: ProgressCallback[] = [];
private _progress = 0;
get progress() { return this._progress; }
set progress(p: number) {
if(p == this._progress) return;
this._progress = p;
this.listeners.forEach(l => l(p));
}
constructor(executor: (resolve: (value: T) => any, reject: (reason: any) => void, progress: (progress: number) => any) => void) {
super((resolve, reject) => executor(
(value: T) => resolve(value),
(reason: any) => reject(reason),
(progress: number) => this.progress = progress
));
}
onProgress(callback: ProgressCallback) {
this.listeners.push(callback);
return this;
}
}

View File

@ -1,4 +1,11 @@
import {TypedEmitter, TypedEvents} from './emitter.ts'; import {
BadRequestError,
CustomError,
ForbiddenError,
InternalServerError,
NotFoundError,
UnauthorizedError
} from './errors.ts';
import {clean} from './objects'; import {clean} from './objects';
export type Interceptor = (request: Response, next: () => void) => void; export type Interceptor = (request: Response, next: () => void) => void;
@ -75,3 +82,14 @@ export class XHR {
}); });
} }
} }
XHR.addInterceptor((resp: Response, next: () => void) => {
const getErr = (e: any) => e.error?.message || e.reason?.message || e.message || e.statusText || e.toString();
if(resp.status == 200) return next();
if(resp.status == 400) throw new BadRequestError(getErr(resp));
if(resp.status == 401) throw new UnauthorizedError(getErr(resp));
if(resp.status == 403) throw new ForbiddenError(getErr(resp));
if(resp.status == 404) throw new NotFoundError(getErr(resp));
if(resp.status == 500) throw new InternalServerError(getErr(resp));
throw new CustomError(getErr(resp), resp.status);
});