extended JS and TS template with Bearer token

This commit is contained in:
2026-03-30 23:32:38 +02:00
parent 394a85ef45
commit c758dc9317
4 changed files with 130 additions and 4 deletions

View File

@ -7,12 +7,63 @@
class <?php echo $this->apiName; ?> {
endpoint = <?php echo sprintf(substr($this->endpoint, 0, 4) == 'http' ? '"%s"' : '%s', $this->endpoint); ?>;
bearerStorageKey = 'apilite_bearer_token';
normalizeBearerToken(token) {
if (typeof token !== 'string') return null;
token = token.trim();
return token === '' ? null : token;
}
getStorage() {
try {
if (typeof window !== 'undefined' && window.localStorage) return window.localStorage;
} catch (error) {
return null;
}
return null;
}
getBearerToken() {
var storage = this.getStorage();
if (storage == null) return null;
return this.normalizeBearerToken(storage.getItem(this.bearerStorageKey));
}
getRequestHeaders(headers = {}) {
var requestHeaders = Object.assign({}, headers);
if (typeof requestHeaders.Authorization === 'undefined') {
var token = this.getBearerToken();
if (token != null) requestHeaders.Authorization = 'Bearer ' + token;
}
return requestHeaders;
}
applyHeaders(xhttp, headers) {
Object.keys(headers).forEach(key => {
var value = headers[key];
if (typeof value === 'undefined' || value === null) return;
xhttp.setRequestHeader(key, value);
});
}
bearerSet(token) {
var storage = this.getStorage();
if (storage == null) return;
token = this.normalizeBearerToken(token);
if (token == null) {
storage.removeItem(this.bearerStorageKey);
return;
}
storage.setItem(this.bearerStorageKey, token);
}
/* ----------------------------------------------------
* General API call
*/
call(method, data, callback) {
var xhttp = new XMLHttpRequest();
var headers = this.getRequestHeaders();
xhttp.withCredentials = true;
xhttp.onreadystatechange = function() {
if (this.readyState === 4) {
@ -31,6 +82,7 @@ class <?php echo $this->apiName; ?> {
form_data.append(key, val);
});
xhttp.open('POST', this.endpoint + '?action=' + method);
this.applyHeaders(xhttp, headers);
xhttp.send(form_data);
}
@ -66,4 +118,4 @@ class <?php echo $this->apiName; ?> {
};
export default new <?php echo $this->apiName; ?>();
export default new <?php echo $this->apiName; ?>();