gitea/web_src/js/modules/fomantic/api.js

70 lines
1.9 KiB
JavaScript
Raw Normal View History

2024-04-14 21:32:23 +02:00
import $ from 'jquery';
2024-04-14 21:34:40 +02:00
import {GET} from '../fetch.js';
2024-04-14 21:32:23 +02:00
import {isObject} from '../../utils.js';
// action: "search"
// cache: true
// debug: false
// on: false
// onAbort: function onAbort(response)
// onError: function error()
// onFailure: function onFailure()
// onResponse: function onResponse(response)
// onSuccess: function onSuccess(response)
// url: "/user/search?active=1&q={query}"
// urlData: Object { query: "si" }
export function initFomanticApi() {
// stand-in for removed api module
// https://github.com/fomantic/Fomantic-UI/blob/2.8.7/src/definitions/modules/dropdown.js
// https://github.com/fomantic/Fomantic-UI/blob/2.8.7/src/definitions/behaviors/api.js
2024-04-14 21:34:40 +02:00
$.fn.api = function (arg0) {
2024-04-14 21:35:06 +02:00
console.info(arg0);
2024-04-14 21:36:54 +02:00
if (arg0 === 'is loading') {
return this._loading;
}
2024-04-14 21:32:23 +02:00
if (arg0 === 'abort') {
this._ac?.abort();
return;
}
if (isObject(arg0)) {
let {url, urlData, onSuccess, onError, onAbort} = arg0;
if (url.includes('{query}') && urlData?.query) {
url = url.replace('{query}', urlData.query);
}
this._data = {url, onSuccess, onError, onAbort};
} else if (arg0 === 'query') {
2024-04-14 21:34:40 +02:00
(async () => {
const {url, onSuccess, onError, onAbort} = this._data;
2024-04-14 21:32:23 +02:00
2024-04-14 21:34:40 +02:00
try {
this._loading = true;
this._ac = new AbortController();
const res = await GET(url, {signal: this.ac.signal});
if (!res.ok) {
onError?.();
}
if (res?.headers?.['content-type']?.startsWith('application/json')) {
onSuccess?.(await res.json());
} else {
onSuccess?.(await res.text());
}
} catch (err) {
this._loading = false;
if (err.name === 'AbortError') {
onAbort?.();
} else {
onError?.();
}
2024-04-14 21:32:23 +02:00
}
2024-04-14 21:34:40 +02:00
})();
2024-04-14 21:32:23 +02:00
}
2024-04-14 21:34:40 +02:00
return this;
2024-04-14 21:32:23 +02:00
};
}