atas/static/apiWrapper.js
2025-01-17 23:02:39 +01:00

110 lines
2.8 KiB
JavaScript

_wrapperVersion = "1.0.0"
_minApiVersion = "1.0.0"
_maxApiVersion = "1.0.0"
_apiConfig = {
"basePath": "/api/v1/"
}
// Generic driver functions
let _api = {
"get": async function(path) {
const options = {
headers: new Headers({'content-type': 'application/json'})
};
const response = await fetch(_apiConfig.basePath + path, options)
// Handle the response
if (!response.ok) {
_testPageFail(response.statusText)
return
}
const result = await response.json()
// Handle the result, was json valid?
if (!result) {
_testPageFail("Invalid JSON response")
return
}
return result;
},
"post": async function(path, data) {
const options = {
method: 'POST',
headers: new Headers({'content-type': 'application/json'}),
body: JSON.stringify(data)
};
const response = await fetch(_apiConfig.basePath + path, options)
// Handle the response
if (!response.ok) {
_testPageFail(response.statusText)
return
}
const result = await response.json()
// Handle the result, was json valid?
if (!result) {
_testPageFail("Invalid JSON response")
return
}
return result;
},
"getAsync": function(path, callback) {
const options = {
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 returnTableDataByTableName(tableName) {
return _api.get(tableName)
}
function returnTableDataByTableNameWithSearch(tableName, search) {
return _api.get(tableName + "?search=" + search)
}
function returnTableDataByTableNameAsync(tableName, callback) {
_api.getAsync(tableName, callback)
}
async function getCountByTable(tableName) {
let result = await(_api.get(tableName + "?count"))
if(typeof result !== 'number') {
_testPageWarn("Count was not a number, was: " + result)
console.warn("Count was not a number, was: " + result)
return -1
}
return result
}
function getRowsByTableAndColumnList(tableName, columnList) {
//return _api.get(tableName + '/rows/' + columnList.join(','))
return undefined
}
function _testPageFail(reason) {
document.getElementById("heroStatus").classList.remove("is-success")
document.getElementById("heroStatus").classList.add("is-danger")
document.getElementById("heroExplainer").innerHTML = "API Wrapper Test Failed, reason: " + reason
}
function _testPageWarn(reason) {
document.getElementById("heroStatus").classList.remove("is-success")
document.getElementById("heroStatus").classList.add("is-warning")
document.getElementById("heroExplainer").innerHTML = "API Wrapper Test Warning, reason: " + reason
}
function getServerVersion() {
return _api.get('version')
}
function createEntry(tableName, data) {
return _api.post(tableName, data)
}