Compare commits
22 Commits
Author | SHA1 | Date | |
---|---|---|---|
8d3b427c1b | |||
87857a01c5 | |||
535e579b43 | |||
2934f86530 | |||
0693397164 | |||
2a878b7962 | |||
7b2d4ba119 | |||
1a4e732fd5 | |||
3a039c935f | |||
ac5b0b8b41 | |||
3f85c9cf7d | |||
1eff60e7dd | |||
1d9ad2ef63 | |||
973a884b3e | |||
6f60f8bd94 | |||
07606cd996 | |||
3ca956e531 | |||
9350c837e5 | |||
86196c3feb | |||
0985ff145e | |||
7cd717fc7d | |||
2fe8cdb96a |
63
.github/workflows/build.yaml
vendored
63
.github/workflows/build.yaml
vendored
@ -9,39 +9,28 @@ jobs:
|
|||||||
build:
|
build:
|
||||||
name: Build NPM Project
|
name: Build NPM Project
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
container:
|
container: node:20-alpine
|
||||||
image: node
|
|
||||||
volumes:
|
|
||||||
- '/mnt/swarm/gitea/runner/cache:/cache'
|
|
||||||
steps:
|
steps:
|
||||||
- name: Clone Repository
|
- name: Clone Repository
|
||||||
uses: ztimson/actions/clone@develop
|
uses: ztimson/actions/clone@develop
|
||||||
|
|
||||||
- name: Restore node_modules
|
- name: Install & Build
|
||||||
uses: ztimson/actions/cache/restore@develop
|
run: |
|
||||||
with:
|
npm i
|
||||||
key: node_modules
|
npm run build
|
||||||
|
|
||||||
- name: Install Dependencies
|
|
||||||
run: npm i
|
|
||||||
|
|
||||||
- name: Build Project
|
|
||||||
run: npm run build
|
|
||||||
|
|
||||||
- name: Test
|
- name: Test
|
||||||
run: npm run test:coverage
|
run: npm run test:coverage
|
||||||
|
|
||||||
- name: Cache node_modules
|
- name: Upload to Registry
|
||||||
uses: ztimson/actions/cache@develop
|
uses: ztimson/actions/npm/publish@develop
|
||||||
with:
|
|
||||||
key: node_modules
|
|
||||||
pattern: node_modules
|
|
||||||
|
|
||||||
- name: Cache Artifacts
|
- name: Upload to NPM
|
||||||
uses: ztimson/actions/cache@develop
|
uses: ztimson/actions/npm/publish@develop
|
||||||
with:
|
with:
|
||||||
key: dist
|
owner: ztimson
|
||||||
pattern: dist
|
registry: https://registry.npmjs.org/
|
||||||
|
token: ${{secrets.NPM_TOKEN}}
|
||||||
tag:
|
tag:
|
||||||
name: Tag Version
|
name: Tag Version
|
||||||
needs: build
|
needs: build
|
||||||
@ -59,31 +48,3 @@ jobs:
|
|||||||
uses: ztimson/actions/tag@develop
|
uses: ztimson/actions/tag@develop
|
||||||
with:
|
with:
|
||||||
tag: ${{env.VERSION}}
|
tag: ${{env.VERSION}}
|
||||||
|
|
||||||
publish:
|
|
||||||
name: Publish
|
|
||||||
needs: build
|
|
||||||
if: ${{github.ref_name}} == 'release'
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
container:
|
|
||||||
image: node
|
|
||||||
volumes:
|
|
||||||
- '/mnt/swarm/gitea/runner/cache:/cache'
|
|
||||||
steps:
|
|
||||||
- name: Clone Repository
|
|
||||||
uses: ztimson/actions/clone@develop
|
|
||||||
|
|
||||||
- name: Restore Artifacts
|
|
||||||
uses: ztimson/actions/cache/restore@develop
|
|
||||||
with:
|
|
||||||
key: dist
|
|
||||||
|
|
||||||
- name: Upload to Registry
|
|
||||||
uses: ztimson/actions/npm/publish@develop
|
|
||||||
|
|
||||||
- name: Upload to NPM
|
|
||||||
uses: ztimson/actions/npm/publish@develop
|
|
||||||
with:
|
|
||||||
owner: ztimson
|
|
||||||
registry: https://registry.npmjs.org/
|
|
||||||
token: ${{secrets.NPM_TOKEN}}
|
|
||||||
|
4
package-lock.json
generated
4
package-lock.json
generated
@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "@ztimson/utils",
|
"name": "@ztimson/utils",
|
||||||
"version": "0.4.0",
|
"version": "0.10.4",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "@ztimson/utils",
|
"name": "@ztimson/utils",
|
||||||
"version": "0.4.0",
|
"version": "0.10.4",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/jest": "^29.5.12",
|
"@types/jest": "^29.5.12",
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ztimson/utils",
|
"name": "@ztimson/utils",
|
||||||
"version": "0.7.2",
|
"version": "0.13.0",
|
||||||
"description": "Utility library",
|
"description": "Utility library",
|
||||||
"author": "Zak Timson",
|
"author": "Zak Timson",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
@ -12,6 +12,13 @@
|
|||||||
"main": "./dist/utils.cjs",
|
"main": "./dist/utils.cjs",
|
||||||
"module": "./dist/utils.mjs",
|
"module": "./dist/utils.mjs",
|
||||||
"types": "./dist/index.d.ts",
|
"types": "./dist/index.d.ts",
|
||||||
|
"exports": {
|
||||||
|
".": {
|
||||||
|
"import": "./dist/utils.mjs",
|
||||||
|
"require": "./dist/utils.cjs",
|
||||||
|
"types": "./dist/index.d.ts"
|
||||||
|
}
|
||||||
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "npx tsc && npx vite build",
|
"build": "npx tsc && npx vite build",
|
||||||
"test": "npx jest",
|
"test": "npx jest",
|
||||||
|
@ -1,10 +1,3 @@
|
|||||||
import {TypedEmitter, TypedEvents} from './emitter';
|
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
@ -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;
|
||||||
|
|
||||||
|
122
src/http.ts
Normal file
122
src/http.ts
Normal file
@ -0,0 +1,122 @@
|
|||||||
|
import {clean} from './objects';
|
||||||
|
import {PromiseProgress} from './promise-progress.ts';
|
||||||
|
|
||||||
|
export type DecodedResponse<T> = Response & {data?: T}
|
||||||
|
|
||||||
|
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;
|
||||||
|
headers?: {[key: string | symbol]: string | null | undefined};
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type HttpDefaults = {
|
||||||
|
headers?: {[key: string | symbol]: string | null | undefined};
|
||||||
|
interceptors?: HttpInterceptor[];
|
||||||
|
url?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Http {
|
||||||
|
private static interceptors: {[key: string]: HttpInterceptor} = {};
|
||||||
|
|
||||||
|
static headers: {[key: string]: string | null | undefined} = {};
|
||||||
|
|
||||||
|
private interceptors: {[key: string]: HttpInterceptor} = {}
|
||||||
|
|
||||||
|
headers: {[key: string]: string | null | undefined} = {}
|
||||||
|
url!: string | null;
|
||||||
|
|
||||||
|
constructor(defaults: HttpDefaults = {}) {
|
||||||
|
this.url = defaults.url ?? null;
|
||||||
|
this.headers = defaults.headers || {};
|
||||||
|
if(defaults.interceptors) {
|
||||||
|
defaults.interceptors.forEach(i => Http.addInterceptor(i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static addInterceptor(fn: HttpInterceptor): () => void {
|
||||||
|
const key = Object.keys(Http.interceptors).length.toString();
|
||||||
|
Http.interceptors[key] = fn;
|
||||||
|
return () => { Http.interceptors[key] = <any>null; }
|
||||||
|
}
|
||||||
|
|
||||||
|
addInterceptor(fn: HttpInterceptor): () => void {
|
||||||
|
const key = Object.keys(this.interceptors).length.toString();
|
||||||
|
this.interceptors[key] = fn;
|
||||||
|
return () => { this.interceptors[key] = <any>null; }
|
||||||
|
}
|
||||||
|
|
||||||
|
request<T>(opts: HttpRequestOptions = {}): PromiseProgress<DecodedResponse<T>> {
|
||||||
|
if(!this.url && !opts.url) throw new Error('URL needs to be set');
|
||||||
|
let url = (opts.url?.startsWith('http') ? opts.url : (this.url || '') + (opts.url || '')).replace(/([^:]\/)\/+/g, '$1');
|
||||||
|
if(opts.fragment) url.includes('#') ? url.replace(/#.*(\?|\n)/g, (match, arg1) => `#${opts.fragment}${arg1}`) : url += '#' + opts.fragment;
|
||||||
|
if(opts.query) {
|
||||||
|
const q = Array.isArray(opts.query) ? opts.query :
|
||||||
|
Object.keys(opts.query).map(k => ({key: k, value: (<any>opts.query)[k]}))
|
||||||
|
url += (url.includes('?') ? '&' : '?') + q.map(q => `${q.key}=${q.value}`).join('&');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prep headers
|
||||||
|
const headers = <any>clean({
|
||||||
|
'Content-Type': !opts.body ? undefined : (opts.body instanceof FormData ? 'multipart/form-data' : 'application/json'),
|
||||||
|
...Http.headers,
|
||||||
|
...this.headers,
|
||||||
|
...opts.headers
|
||||||
|
});
|
||||||
|
|
||||||
|
if(typeof opts.body == 'object' && opts.body != null && headers['Content-Type'] == 'application/json')
|
||||||
|
opts.body = JSON.stringify(opts.json);
|
||||||
|
|
||||||
|
// Send request
|
||||||
|
return new PromiseProgress((res, rej, prog) => {
|
||||||
|
fetch(url, {
|
||||||
|
headers,
|
||||||
|
method: opts.method || (opts.body ? 'POST' : 'GET'),
|
||||||
|
body: opts.body
|
||||||
|
}).then(async (resp: DecodedResponse<T>) => {
|
||||||
|
console.log('done!');
|
||||||
|
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;
|
||||||
|
|
||||||
|
const reader = resp.body?.getReader();
|
||||||
|
const stream = new ReadableStream({
|
||||||
|
start(controller) {
|
||||||
|
function push() {
|
||||||
|
reader?.read().then(({done, value}) => {
|
||||||
|
if(done) return controller.close();
|
||||||
|
loaded += value.byteLength;
|
||||||
|
prog(loaded / total);
|
||||||
|
controller.enqueue(value);
|
||||||
|
push();
|
||||||
|
}).catch(error => {
|
||||||
|
controller.error(error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
push();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = new Response(stream);
|
||||||
|
|
||||||
|
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);
|
||||||
|
})
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
@ -3,9 +3,12 @@ export * from './aset';
|
|||||||
export * from './download';
|
export * from './download';
|
||||||
export * from './emitter';
|
export * from './emitter';
|
||||||
export * from './errors';
|
export * from './errors';
|
||||||
|
export * from './http.ts';
|
||||||
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 './upload.ts';
|
||||||
|
45
src/math.ts
Normal file
45
src/math.ts
Normal 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]));
|
||||||
|
}
|
@ -35,6 +35,27 @@ export function deepCopy<T>(value: T): T {
|
|||||||
return JSON.parse(JSON.stringify(value));
|
return JSON.parse(JSON.stringify(value));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Merge any number of objects into the target
|
||||||
|
*
|
||||||
|
* @param target Destination of all properties
|
||||||
|
* @param sources Objects that will copied into target
|
||||||
|
* @return {any} The des
|
||||||
|
*/
|
||||||
|
export function deepMerge<T>(target: any, ...sources: any[]): T {
|
||||||
|
sources.forEach(s => {
|
||||||
|
for(const key in s) {
|
||||||
|
if(s[key] && typeof s[key] == 'object' && !Array.isArray(s[key])) {
|
||||||
|
if(!target[key]) target[key] = {};
|
||||||
|
deepMerge(target[key], s[key]);
|
||||||
|
} else {
|
||||||
|
target[key] = s[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return target;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get/set a property of an object using dot notation
|
* Get/set a property of an object using dot notation
|
||||||
*
|
*
|
||||||
|
52
src/promise-progress.ts
Normal file
52
src/promise-progress.ts
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
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,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
static from<T>(promise: Promise<T>): PromiseProgress<T> {
|
||||||
|
if(promise instanceof PromiseProgress) return promise;
|
||||||
|
return new PromiseProgress<T>((res, rej) => promise
|
||||||
|
.then((...args) => res(...args))
|
||||||
|
.catch((...args) => rej(...args)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private from(promise: Promise<T>): PromiseProgress<T> {
|
||||||
|
const newPromise = PromiseProgress.from(promise);
|
||||||
|
this.onProgress(p => newPromise.progress = p);
|
||||||
|
return newPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
onProgress(callback: ProgressCallback) {
|
||||||
|
this.listeners.push(callback);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
then(res?: (v: T) => any, rej?: (err: any) => any): PromiseProgress<any> {
|
||||||
|
const resp = super.then(res, rej);
|
||||||
|
return this.from(resp);
|
||||||
|
}
|
||||||
|
|
||||||
|
catch(rej?: (err: any) => any): PromiseProgress<any> {
|
||||||
|
return this.from(super.catch(rej));
|
||||||
|
}
|
||||||
|
|
||||||
|
finally(res?: () => any): PromiseProgress<any> {
|
||||||
|
return this.from(super.finally(res));
|
||||||
|
}
|
||||||
|
}
|
25
src/upload.ts
Normal file
25
src/upload.ts
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
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);
|
||||||
|
});
|
||||||
|
}
|
77
src/xhr.ts
77
src/xhr.ts
@ -1,77 +0,0 @@
|
|||||||
import {TypedEmitter, TypedEvents} from './emitter.ts';
|
|
||||||
import {clean} from './objects';
|
|
||||||
|
|
||||||
export type Interceptor = (request: Response, next: () => void) => void;
|
|
||||||
|
|
||||||
export type RequestOptions = {
|
|
||||||
url?: string;
|
|
||||||
method?: 'GET' | 'POST' | 'PATCH' | 'DELETE';
|
|
||||||
body?: any;
|
|
||||||
headers?: {[key: string | symbol]: string | null | undefined};
|
|
||||||
skipConverting?: boolean;
|
|
||||||
[key: string]: any;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type XhrOptions = {
|
|
||||||
headers?: {[key: string | symbol]: string | null | undefined};
|
|
||||||
interceptors?: Interceptor[];
|
|
||||||
url?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class XHR {
|
|
||||||
private static interceptors: {[key: string]: Interceptor} = {};
|
|
||||||
|
|
||||||
static headers: {[key: string]: string | null | undefined} = {};
|
|
||||||
|
|
||||||
private interceptors: {[key: string]: Interceptor} = {}
|
|
||||||
|
|
||||||
headers: {[key: string]: string | null | undefined} = {}
|
|
||||||
|
|
||||||
constructor(public readonly opts: XhrOptions = {}) {
|
|
||||||
this.headers = opts.headers || {};
|
|
||||||
if(opts.interceptors) {
|
|
||||||
opts.interceptors.forEach(i => XHR.addInterceptor(i));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static addInterceptor(fn: Interceptor): () => void {
|
|
||||||
const key = Object.keys(XHR.interceptors).length.toString();
|
|
||||||
XHR.interceptors[key] = fn;
|
|
||||||
return () => { XHR.interceptors[key] = <any>null; }
|
|
||||||
}
|
|
||||||
|
|
||||||
addInterceptor(fn: Interceptor): () => void {
|
|
||||||
const key = Object.keys(this.interceptors).length.toString();
|
|
||||||
this.interceptors[key] = fn;
|
|
||||||
return () => { this.interceptors[key] = <any>null; }
|
|
||||||
}
|
|
||||||
|
|
||||||
async request<T>(opts: RequestOptions = {}): Promise<T> {
|
|
||||||
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');
|
|
||||||
|
|
||||||
// Prep headers
|
|
||||||
const headers = <any>clean({
|
|
||||||
'Content-Type': (opts.body && !(opts.body instanceof FormData)) ? 'application/json' : undefined,
|
|
||||||
...XHR.headers,
|
|
||||||
...this.headers,
|
|
||||||
...opts.headers
|
|
||||||
});
|
|
||||||
|
|
||||||
// Send request
|
|
||||||
return fetch(url, {
|
|
||||||
headers,
|
|
||||||
method: opts.method || (opts.body ? 'POST' : 'GET'),
|
|
||||||
body: (headers['Content-Type']?.startsWith('application/json') && opts.body) ? JSON.stringify(opts.body) : opts.body
|
|
||||||
}).then(async resp => {
|
|
||||||
for(let fn of [...Object.values(XHR.interceptors), ...Object.values(this.interceptors)]) {
|
|
||||||
await new Promise<void>(res => fn(resp, () => res()));
|
|
||||||
}
|
|
||||||
|
|
||||||
if(!resp.ok) throw new Error(resp.statusText);
|
|
||||||
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 <any>resp.text();
|
|
||||||
return resp;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
Reference in New Issue
Block a user