diff --git a/fetch-mixin.js b/fetch-mixin.js index 8416649..f56c039 100644 --- a/fetch-mixin.js +++ b/fetch-mixin.js @@ -5,40 +5,44 @@ export const fetchMixin = function(superClass) { this.__abortControllers = new Map(); } - get(url) { - return fetch(url).then(response => response.json()); + get(url, overwrite = true) { + return this.do('GET', url, null, overwrite); } head(url) { return fetch(url, { method: 'HEAD' }); } - async post(url, data, overwrite = true) { - this.__cancelRunningRequest(url); + post(url, data, overwrite = true) { + return this.do('POST', url, data, overwrite); + } + + async do(method, url, data, overwrite = true) { + this.__cancelRunningRequest(method, url); if (overwrite === true) { const ac = new AbortController(); - this.__abortControllers.set(url, ac); + this.__abortControllers.set(`${method}:${url}`, ac); } try { const reqOptions = { - method: 'POST', - signal: overwrite ? this.__abortControllers.get(url).signal : null, + method, + signal: overwrite ? this.__abortControllers.get(`${method}:${url}`).signal : null, mode: 'cors', cache: 'no-cache', headers: { 'Content-Type': 'application/json; charset=utf-8' }, referrer: 'no-referrer', - body: JSON.stringify(data) + body: data ? JSON.stringify(data) : undefined }; document.dispatchEvent(new CustomEvent('before-request', { detail: reqOptions, bubbles: true, composed: true })); const result = await fetch(url, reqOptions).then(response => response.json()); - this.__abortControllers.delete(url); + this.__abortControllers.delete(`${method}:${url}`); if (result.statusCode === 500) { console.error(result); @@ -49,22 +53,27 @@ export const fetchMixin = function(superClass) { if (err.name === 'AbortError') { return { statusCode: -1, error: err }; } else { - this.__abortControllers.delete(url); + this.__abortControllers.delete(`${method}:${url}`); return { statusCode: null, error: err }; } } } - isInFlight(url) { - return Boolean(this.__abortControllers.get(url)); + isInFlight(method, url) { + if (url === undefined) { + console.error('Missing url parameter'); + return false; + } + + return Boolean(this.__abortControllers.get(`${method}:${url}`)); } - __cancelRunningRequest(url) { - if (this.__abortControllers.has(url)) { + __cancelRunningRequest(method, url) { + if (this.__abortControllers.has(`${method}:${url}`)) { try { - this.__abortControllers.get(url).abort(); + this.__abortControllers.get(`${method}:${url}`).abort(); } catch (err) { } - this.__abortControllers.delete(url); + this.__abortControllers.delete(`${method}:${url}`); } } }; diff --git a/package.json b/package.json index 322e81d..ae5b213 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@tp/helpers", - "version": "1.3.0", + "version": "2.1.0", "description": "", "main": "closest.js", "scripts": {