atas/static/apiWrapper.js

176 lines
4.8 KiB
JavaScript
Raw Normal View History

2025-01-30 00:32:10 +01:00
_wrapperVersion = '1.0.0';
_minApiVersion = '1.0.0';
_maxApiVersion = '1.0.0';
_defaultTTL = 60000;
2025-01-17 23:02:39 +01:00
_apiConfig = {
2025-01-30 00:32:10 +01:00
basePath: '/api/v1/'
};
if (!window.localStorage) {
console.warn('Local Storage is not available, some features may not work');
2025-01-17 23:02:39 +01:00
}
// Generic driver functions
let _api = {
2025-01-30 00:32:10 +01:00
get: async function (path) {
2025-01-17 23:02:39 +01:00
const options = {
2025-01-30 00:32:10 +01:00
headers: new Headers({ 'content-type': 'application/json' })
};
const response = await fetch(_apiConfig.basePath + path, options);
2025-01-17 23:02:39 +01:00
// Handle the response
if (!response.ok) {
2025-01-30 00:32:10 +01:00
_testPageFail(response.statusText);
return;
2025-01-17 23:02:39 +01:00
}
2025-01-30 00:32:10 +01:00
const result = await response.json();
2025-01-17 23:02:39 +01:00
// Handle the result, was json valid?
if (!result) {
2025-01-30 00:32:10 +01:00
_testPageFail('Invalid JSON response');
return;
2025-01-17 23:02:39 +01:00
}
return result;
2025-01-30 00:32:10 +01:00
},
post: async function (path, data) {
2025-01-17 23:02:39 +01:00
const options = {
method: 'POST',
2025-01-30 00:32:10 +01:00
headers: new Headers({ 'content-type': 'application/json' }),
2025-01-17 23:02:39 +01:00
body: JSON.stringify(data)
2025-01-30 00:32:10 +01:00
};
const response = await fetch(_apiConfig.basePath + path, options);
2025-01-17 23:02:39 +01:00
// Handle the response
if (!response.ok) {
2025-01-30 00:32:10 +01:00
_testPageFail(response.statusText);
return;
2025-01-17 23:02:39 +01:00
}
2025-01-30 00:32:10 +01:00
const result = await response.json();
2025-01-17 23:02:39 +01:00
// Handle the result, was json valid?
if (!result) {
2025-01-30 00:32:10 +01:00
_testPageFail('Invalid JSON response');
return;
2025-01-17 23:02:39 +01:00
}
return result;
},
2025-01-30 00:32:10 +01:00
getAsync: function (path, callback) {
2025-01-17 23:02:39 +01:00
const options = {
2025-01-30 00:32:10 +01:00
headers: new Headers({ 'content-type': 'application/json' })
};
fetch(_apiConfig.basePath + path, options)
.then((response) => response.json())
.then((data) => callback(data))
.catch((error) => _testPageFail(error));
}
};
function getApiDescriptionByTable(tableName) {
const keyDesc = `desc:${tableName}`;
const keyTime = `${keyDesc}:time`;
const keyTTL = `${keyDesc}:ttl`;
// Retrieve cached data
const description = JSON.parse(localStorage.getItem(keyDesc));
const timeCreated = parseInt(localStorage.getItem(keyTime));
const ttl = parseInt(localStorage.getItem(keyTTL));
// Check if valid cached data exists
if (description && timeCreated && ttl) {
const currentTime = Date.now();
const age = currentTime - parseInt(timeCreated, 10);
if (age < parseInt(ttl, 10)) {
// Return cached data immediately
return Promise.resolve(description);
} else {
console.warn('Cached description expired; fetching new data');
// Fetch new data, update cache, and return it
return fetchAndUpdateCache(tableName);
}
} else {
console.warn('No cached description; fetching from server');
// Fetch data, update cache, and return it
return fetchAndUpdateCache(tableName);
2025-01-17 23:02:39 +01:00
}
2025-01-30 00:32:10 +01:00
function fetchAndUpdateCache(tableName) {
return _api
.get(`${tableName}/describe`)
.then((data) => {
if (data) {
// Update local storage with new data
localStorage.setItem(keyDesc, JSON.stringify(data));
localStorage.setItem(keyTime, Date.now().toString());
localStorage.setItem(keyTTL, '60000'); // 60 seconds TTL
}
return data; // Return the fetched data
})
.catch((error) => {
console.error('Failed to fetch description:', error);
// Fallback to cached data if available (even if expired)
return description || null;
});
}
}
2025-01-17 23:02:39 +01:00
function returnTableDataByTableName(tableName) {
2025-01-30 00:32:10 +01:00
return _api.get(tableName);
2025-01-17 23:02:39 +01:00
}
function returnTableDataByTableNameWithSearch(tableName, search) {
2025-01-30 00:32:10 +01:00
return _api.get(tableName + '?search=' + search);
}
2025-01-17 23:02:39 +01:00
function returnTableDataByTableNameAsync(tableName, callback) {
2025-01-30 00:32:10 +01:00
_api.getAsync(tableName, callback);
2025-01-17 23:02:39 +01:00
}
async function getCountByTable(tableName) {
2025-01-30 00:32:10 +01:00
// Stored in `data:count:${tableName}`
let result = await _api.get(tableName + '?count=true');
if (typeof result !== 'number') {
_testPageWarn('Count was not a number, was: ' + result);
console.warn('Count was not a number, was: ' + result);
return -1;
2025-01-17 23:02:39 +01:00
}
2025-01-30 00:32:10 +01:00
return result;
2025-01-17 23:02:39 +01:00
}
function getRowsByTableAndColumnList(tableName, columnList) {
2025-01-30 00:32:10 +01:00
//return _api.get(tableName + '/rows/' + columnList.join(','))
return undefined;
2025-01-17 23:02:39 +01:00
}
function _testPageFail(reason) {
2025-01-30 00:32:10 +01:00
document.getElementById('heroStatus').classList.remove('is-success');
document.getElementById('heroStatus').classList.add('is-danger');
2025-01-17 23:02:39 +01:00
2025-01-30 00:32:10 +01:00
document.getElementById('heroExplainer').innerHTML = 'API Wrapper Test Failed, reason: ' + reason;
2025-01-17 23:02:39 +01:00
}
function _testPageWarn(reason) {
2025-01-30 00:32:10 +01:00
document.getElementById('heroStatus').classList.remove('is-success');
document.getElementById('heroStatus').classList.add('is-warning');
2025-01-17 23:02:39 +01:00
2025-01-30 00:32:10 +01:00
document.getElementById('heroExplainer').innerHTML = 'API Wrapper Test Warning, reason: ' + reason;
2025-01-17 23:02:39 +01:00
}
function getServerVersion() {
2025-01-30 00:32:10 +01:00
return _api.get('version');
2025-01-17 23:02:39 +01:00
}
function createEntry(tableName, data) {
2025-01-30 00:32:10 +01:00
invalidateCache(tableName);
return _api.post(tableName, data);
2025-01-17 23:02:39 +01:00
}
2025-01-30 00:32:10 +01:00
function invalidateCache(tableName) {
const keyDesc = `desc:${tableName}`;
const keyTime = `${keyDesc}:time`;
const keyTTL = `${keyDesc}:ttl`;
localStorage.removeItem(keyDesc);
localStorage.removeItem(keyTime);
localStorage.removeItem(keyTTL);
}