Compare commits

...

19 Commits

Author SHA1 Message Date
adcd6eaf79 Added PUT method to http helper
All checks were successful
Build / Build NPM Project (push) Successful in 30s
Build / Tag Version (push) Successful in 7s
2024-09-11 17:34:56 -04:00
afb6ca0803 Added function to create errors from status codes
All checks were successful
Build / Build NPM Project (push) Successful in 25s
Build / Tag Version (push) Successful in 6s
2024-09-04 18:48:15 -04:00
e699f8a634 Added new error codes
All checks were successful
Build / Build NPM Project (push) Successful in 45s
Build / Tag Version (push) Successful in 6s
2024-09-04 10:47:44 -04:00
c7dd91e9cd Added new error codes
Some checks failed
Build / Tag Version (push) Blocked by required conditions
Build / Build NPM Project (push) Has been cancelled
2024-09-04 10:47:36 -04:00
20f36cc573 Added some doc strings & sleepUntil function
All checks were successful
Build / Build NPM Project (push) Successful in 50s
Build / Tag Version (push) Successful in 7s
2024-08-27 11:41:22 -04:00
57446ef09a bump
All checks were successful
Build / Build NPM Project (push) Successful in 29s
Build / Tag Version (push) Successful in 7s
2024-08-21 11:11:51 -04:00
6d13df39f5 Added JSONAttemptParse & fixed uploadProgress response
All checks were successful
Build / Build NPM Project (push) Successful in 28s
Build / Tag Version (push) Successful in 7s
2024-08-17 14:21:05 -04:00
2d63db0ebb Added formData helper
All checks were successful
Build / Build NPM Project (push) Successful in 28s
Build / Tag Version (push) Successful in 7s
2024-08-15 12:55:57 -04:00
535fc0271e Messing around with http decoding
All checks were successful
Build / Build NPM Project (push) Successful in 24s
Build / Tag Version (push) Successful in 7s
2024-08-13 15:41:47 -04:00
d587b92ea4 Messing around with http decoding
All checks were successful
Build / Build NPM Project (push) Successful in 24s
Build / Tag Version (push) Successful in 7s
2024-08-13 15:38:20 -04:00
26c6084052 Messing around with http decoding
All checks were successful
Build / Build NPM Project (push) Successful in 24s
Build / Tag Version (push) Successful in 7s
2024-08-13 15:21:56 -04:00
874bba59d3 Messing around with http decoding
All checks were successful
Build / Build NPM Project (push) Successful in 24s
Build / Tag Version (push) Successful in 7s
2024-08-13 15:19:07 -04:00
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
10 changed files with 295 additions and 93 deletions

4
package-lock.json generated
View File

@ -1,12 +1,12 @@
{ {
"name": "@ztimson/utils", "name": "@ztimson/utils",
"version": "0.10.4", "version": "0.15.3",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "@ztimson/utils", "name": "@ztimson/utils",
"version": "0.10.4", "version": "0.15.3",
"license": "MIT", "license": "MIT",
"devDependencies": { "devDependencies": {
"@types/jest": "^29.5.12", "@types/jest": "^29.5.12",

View File

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

View File

@ -1,57 +1,108 @@
/**
* An array which functions as a set. It guarantees unique elements
* and provides set functions for comparisons
*/
export class ASet<T> extends Array { export class ASet<T> extends Array {
/** Number of elements in set */
get size() { get size() {
return this.length; return this.length;
} }
/**
* Array to create set from, duplicate values will be removed
* @param {T[]} elements Elements which will be added to set
*/
constructor(elements: T[] = []) { constructor(elements: T[] = []) {
super(); super();
if(!!elements?.['forEach']) if(!!elements?.['forEach'])
elements.forEach(el => this.add(el)); elements.forEach(el => this.add(el));
} }
/**
* Add single element to set if unique
* @param {T} el Element to add
*/
add(el: T) { add(el: T) {
if(!this.has(el)) this.push(el); if(!this.has(el)) this.push(el);
} }
/**
* Delete element from set
* @param {T} el Element that will be deleted
*/
delete(el: T) { delete(el: T) {
const index = this.indexOf(el); const index = this.indexOf(el);
if(index != -1) this.slice(index, 1); if(index != -1) this.slice(index, 1);
} }
/**
* Create list of elements this set has which the comparison set does not
* @param {ASet<T>} set Set to compare against
* @return {ASet<T>} Different elements
*/
difference(set: ASet<T>) { difference(set: ASet<T>) {
return new ASet<T>(this.reduce((acc, el) => { return new ASet<T>(this.filter(el => !set.has(el)));
if(!set.has(el)) acc.push(el);
return acc;
}, []));
} }
/**
* Check if set includes element
* @param {T} el Element to look for
* @return {boolean} True if element was found, false otherwise
*/
has(el: T) { has(el: T) {
return this.indexOf(el) != -1; return this.indexOf(el) != -1;
} }
/**
* Create list of elements this set has in common with the comparison set
* @param {ASet<T>} set Set to compare against
* @return {boolean} Set of common elements
*/
intersection(set: ASet<T>) { intersection(set: ASet<T>) {
return new ASet<T>(this.reduce((acc, el) => { return new ASet<T>(this.filter(el => set.has(el)));
if(set.has(el)) acc.push(el);
return acc;
}, []));
} }
/**
* Check if this set has no elements in common with the comparison set
* @param {ASet<T>} set Set to compare against
* @return {boolean} True if nothing in common, false otherwise
*/
isDisjointFrom(set: ASet<T>) { isDisjointFrom(set: ASet<T>) {
return this.intersection(set).size == 0; return this.intersection(set).size == 0;
} }
/**
* Check if all elements in this set are included in the comparison set
* @param {ASet<T>} set Set to compare against
* @return {boolean} True if all elements are included, false otherwise
*/
isSubsetOf(set: ASet<T>) { isSubsetOf(set: ASet<T>) {
return this.findIndex(el => !set.has(el)) == -1; return this.findIndex(el => !set.has(el)) == -1;
} }
/**
* Check if all elements from comparison set are included in this set
* @param {ASet<T>} set Set to compare against
* @return {boolean} True if all elements are included, false otherwise
*/
isSuperset(set: ASet<T>) { isSuperset(set: ASet<T>) {
return set.findIndex(el => !this.has(el)) == -1; return set.findIndex(el => !this.has(el)) == -1;
} }
/**
* Create list of elements that are only in one set but not both (XOR)
* @param {ASet<T>} set Set to compare against
* @return {ASet<T>} New set of unique elements
*/
symmetricDifference(set: ASet<T>) { symmetricDifference(set: ASet<T>) {
return new ASet([...this.difference(set), ...set.difference(this)]); return new ASet([...this.difference(set), ...set.difference(this)]);
} }
/**
* Create joined list of elements included in this & the comparison set
* @param {ASet<T>} set Set join
* @return {ASet<T>} New set of both previous sets combined
*/
union(set: ASet<T> | Array<T>) { union(set: ASet<T> | Array<T>) {
return new ASet([...this, ...set]); return new ASet([...this, ...set]);
} }

View File

@ -53,6 +53,18 @@ export class UnauthorizedError extends CustomError {
} }
} }
export class PaymentRequiredError extends CustomError {
static code = 402;
constructor(message: string = 'Payment Required') {
super(message);
}
static instanceof(err: Error) {
return (<any>err).constructor.code == this.code;
}
}
export class ForbiddenError extends CustomError { export class ForbiddenError extends CustomError {
static code = 403; static code = 403;
@ -77,6 +89,30 @@ export class NotFoundError extends CustomError {
} }
} }
export class MethodNotAllowedError extends CustomError {
static code = 405;
constructor(message: string = 'Method Not Allowed') {
super(message);
}
static instanceof(err: Error) {
return (<any>err).constructor.code == this.code;
}
}
export class NotAcceptableError extends CustomError {
static code = 406;
constructor(message: string = 'Not Acceptable') {
super(message);
}
static instanceof(err: Error) {
return (<any>err).constructor.code == this.code;
}
}
export class InternalServerError extends CustomError { export class InternalServerError extends CustomError {
static code = 500; static code = 500;
@ -88,3 +124,89 @@ export class InternalServerError extends CustomError {
return (<any>err).constructor.code == this.code; return (<any>err).constructor.code == this.code;
} }
} }
export class NotImplementedError extends CustomError {
static code = 501;
constructor(message: string = 'Not Implemented') {
super(message);
}
static instanceof(err: Error) {
return (<any>err).constructor.code == this.code;
}
}
export class BadGatewayError extends CustomError {
static code = 502;
constructor(message: string = 'Bad Gateway') {
super(message);
}
static instanceof(err: Error) {
return (<any>err).constructor.code == this.code;
}
}
export class ServiceUnavailableError extends CustomError {
static code = 503;
constructor(message: string = 'Service Unavailable') {
super(message);
}
static instanceof(err: Error) {
return (<any>err).constructor.code == this.code;
}
}
export class GatewayTimeoutError extends CustomError {
static code = 504;
constructor(message: string = 'Gateway Timeout') {
super(message);
}
static instanceof(err: Error) {
return (<any>err).constructor.code == this.code;
}
}
/**
* Create the correct error object from a status code
* @param {number} code Will be converted to respective error (ex. 404 -> NotFoundError)
* @param {string} message Override default error message
* @return {CustomError} The proper error type
*/
export function errorFromCode(code: number, message?: string) {
if(code >= 200 && code < 300) return null;
switch(code) {
case 400:
return new BadRequestError(message);
case 401:
return new UnauthorizedError(message);
case 402:
return new PaymentRequiredError(message);
case 403:
return new ForbiddenError(message);
case 404:
return new NotFoundError(message);
case 405:
return new MethodNotAllowedError(message);
case 406:
return new NotAcceptableError(message);
case 500:
return new InternalServerError(message);
case 501:
return new NotImplementedError(message);
case 502:
return new BadGatewayError(message);
case 503:
return new ServiceUnavailableError(message);
case 504:
return new GatewayTimeoutError(message);
default:
return new CustomError(message, code);
}
}

View File

@ -1,4 +1,5 @@
import {PromiseProgress} from './promise-progress.ts'; import {deepCopy, JSONAttemptParse} from './objects.ts';
import {PromiseProgress} from './promise-progress';
export function download(href: any, name: string) { export function download(href: any, name: string) {
const a = document.createElement('a'); const a = document.createElement('a');
@ -31,24 +32,25 @@ export function fileBrowser(options: {accept?: string, multiple?: boolean} = {})
}); });
} }
export function uploadWithProgress(options: { export function uploadWithProgress<T>(options: {
url: string; url: string;
file: File; files: File[];
headers?: {[key: string]: string}; headers?: {[key: string]: string};
withCredentials?: boolean; withCredentials?: boolean;
}) { }): PromiseProgress<T> {
return new PromiseProgress((res, rej, prog) => { return new PromiseProgress<T>((res, rej, prog) => {
const xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
const formData = new FormData(); const formData = new FormData();
formData.append('file', options.file); options.files.forEach(f => formData.append('file', f));
xhr.withCredentials = !!options.withCredentials 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('progress', (event) => event.lengthComputable ? prog(event.loaded / event.total) : null);
xhr.upload.addEventListener('load', (resp) => res(resp)); xhr.addEventListener('loadend', () => res(<T>JSONAttemptParse(xhr.responseText)));
xhr.upload.addEventListener('error', (err) => rej(err)); xhr.addEventListener('error', () => rej(JSONAttemptParse(xhr.responseText)));
xhr.addEventListener('timeout', () => rej({error: 'Request timed out'}));
xhr.open('POST', options.url); xhr.open('POST', options.url);
Object.entries(options.headers || {}).forEach(([key, value]) => xhr.setRequestHeader(key, value));
xhr.send(formData); xhr.send(formData);
}); });
} }

View File

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

View File

@ -1,17 +1,5 @@
import {md5} from './string'; 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 * Get profile image from Gravatar
* *

View File

@ -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 * 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[] = []; let cache: any[] = [];
return JSON.parse(JSON.stringify(obj, (key, value) => { return JSON.parse(JSON.stringify(obj, (key, value) => {
if (typeof value === 'object' && value !== null) { if (typeof value === 'object' && value !== null) {
@ -185,3 +201,15 @@ export function sanitizedJSON(obj: any, space?: number) {
return value; return value;
}, space)); }, 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('&');
}

View File

@ -1,32 +1,3 @@
/**
* Calculate the number of milliseconds until date/time
*
* @param {Date | number} date - Target
* @returns {number} - Number of milliseconds until target
*/
export function timeUntil(date: Date | number): number {
return (date instanceof Date ? date.getTime() : date) - (new Date()).getTime();
}
/**
* Use in conjunction with `await` to pause an async script
*
* @example
* ```ts
* async () => {
* ...
* await sleep(1000) // Pause for 1 second
* ...
* }
* ```
*
* @param {number} ms - Time to pause for in milliseconds
* @returns {Promise<unknown>} - Resolves promise when it's time to resume
*/
export function sleep(ms: number) {
return new Promise(res => setTimeout(res, ms));
}
export function formatDate(date: Date | number | string) { export function formatDate(date: Date | number | string) {
const d = date instanceof Date ? date : new Date(date); const d = date instanceof Date ? date : new Date(date);
return new Intl.DateTimeFormat("en-us", { return new Intl.DateTimeFormat("en-us", {
@ -38,3 +9,44 @@ export function formatDate(date: Date | number | string) {
hour12: true hour12: true
}).format(d); }).format(d);
} }
/**
* Use in conjunction with `await` to pause an async script
*
* @example
* ```js
* await sleep(1000) // Pause for 1 second
* ```
* @param {number} ms - Time to pause for in milliseconds
* @returns {Promise<unknown>} - Resolves promise when it's time to resume
*/
export function sleep(ms: number): Promise<void> {
return new Promise(res => setTimeout(res, ms));
}
/**
* Sleep while function returns true
*
* @example
* ```js
* let loading = true;
* setTimeout(() => wait = false, 1000);
* await sleepUntil(() => loading); // Won't continue until loading flag is false
* ```
* @param {() => boolean} fn Return true to continue
* @param {number} checkInterval Run function ever x milliseconds
* @return {Promise<void>} Callback when sleep is over
*/
export async function sleepUntil(fn : () => boolean, checkInterval=100): Promise<void> {
while(fn()) await sleep(checkInterval);
}
/**
* Calculate the number of milliseconds until date/time
*
* @param {Date | number} date - Target
* @returns {number} - Number of milliseconds until target
*/
export function timeUntil(date: Date | number): number {
return (date instanceof Date ? date.getTime() : date) - (new Date()).getTime();
}

View File

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