Giancarlo 7 years ago
parent
commit
38770ff81a
2 changed files with 56 additions and 0 deletions
  1. 1 0
      ui/admin/package.json
  2. 55 0
      ui/frontend/js/OMGUtils.js

+ 1 - 0
ui/admin/package.json

@@ -6,6 +6,7 @@
 	"description": "OM-Link Admin Module",
 	"author": "Open Mind",
 	"scripts": {
+		"clean": "shx --silent rm -rf node_modules masterpage.tpl",
 		"buildDev": "webpack --mode=none --display-error-details",
 		"buildProd": "webpack --mode=production --display-error-details",
 		"watch": "webpack --mode=none --display-error-details --watch"

+ 55 - 0
ui/frontend/js/OMGUtils.js

@@ -0,0 +1,55 @@
+export const fetchHeaders = {
+	'Accept': 'text/html',
+	'Content-Type': 'text/html',
+	'X-Requested-With': 'XMLHttpRequest',
+	'Cache-Control': 'no-cache',
+	'Pragma': 'no-cache',
+	'Expires': '0'
+};
+
+/**
+ * Make an AJAX request.
+ *
+ * If error, catch return a promise error object:
+ *
+ *  .catch(err => alert(`${err.url}\n\n${err.status} (${err.statusText})`));
+ *
+ * @param url URL of RESTful api to call
+ * @param options the fetch() options
+ * @param complete Promise resolve callback
+ * @param error Promise reject callback
+ * @returns Object {Promise, signal: AbortController}
+ */
+export function AjaxReq(url, options, complete, error) {
+	let fetchSignal = new AbortController();
+	let defaults = {
+		headers: fetchHeaders,
+		signal: fetchSignal.signal
+	};
+	// Extend default options
+	Object.assign(defaults, options);
+
+	let fetchPromise = fetch(url, defaults)
+		.then(resp => {
+			if (resp.status === 200)
+				return resp.json();
+			else
+				return Promise.reject(resp);
+		})
+		.catch(err => {
+			if (err.name === 'AbortError')
+				return;
+			if (err.url !== undefined)
+				toastr.error(err.url, `${err.status} (${err.statusText})`);
+			else
+				toastr.error(err);
+		});
+
+	// Add some properties to return value
+	return {
+		fetchPromise: () => fetchPromise,
+		abort: function () {
+			fetchSignal.abort()
+		}
+	};
+}