Source

fetch/AdmFetch.js

"use strict"

/**
 *	----------------------------------------------------------------------------------------------
 *	Imports
 * 	----------------------------------------------------------------------------------------------
 */


/**
 *	----------------------------------------------------------------------------------------------
 *	Class AdmFetch 
 * 	----------------------------------------------------------------------------------------------
 */
class AdmFetch{

	constructor(options = {}){ 
		this.headers = options.headers || new Headers();
		this.cache = options.cache || 'no-cache';
		this.mode = options.mode || 'cors';
	}
	  
	fetchJSON(url, method, data, raw){
		const options = {
			headers: this.headers,
			mode: this.mode,
			cache: this.cache,
			method: method
		}
		
		if(data){
			if(method === "GET" || method === "DELETE"){
				url += `?${new URLSearchParams(data).toString()}`;		
			}
			else{
				options.body = (raw) ? data : JSON.stringify(data);
			}
		}

		return fetch(url, options)
			.then(async response => {
				let result = await response.json();
				if(!response.ok){ throw result; }
				return result; 
			})
	}

	makeFetch(url, method, data){
		console.warn("DeprecationWarning: AdmFetch:makeFetch is deprecated. Use AdmFetch:fetchJSON instead");
		const options = {
			headers: this.headers,
			mode: this.mode,
			cache: this.cache,
			method: method
		}
		
		if(data){
			if(method === "GET" || method === "DELETE"){
				url += `?${new URLSearchParams(data).toString()}`;		
			}
			else{
				options.body = JSON.stringify(data);
			}
		}

		return fetch(url, options)
			.then(async response => {
				let result = await response.json();
				if(!response.ok){ throw result; }
				return result; 
			})
	}
}

export {AdmFetch}