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

@ -152,8 +152,72 @@ export interface APIliteHelpResponse {
msg: string;
}
type APIliteRequestHeaders = Partial<Record<string, string>>;
class <?php echo $this->apiName; ?> {
endpoint: string = <?php echo sprintf(substr($this->endpoint, 0, 4) == 'http' ? '"%s"' : '%s', $this->endpoint); ?>;
private readonly bearerStorageKey: string = 'apilite_bearer_token';
private normalizeBearerToken(token: string | null | undefined): string | null {
if (typeof token !== 'string') {
return null;
}
const normalizedToken = token.trim();
return normalizedToken === '' ? null : normalizedToken;
}
private getStorage(): Storage | null {
try {
if (typeof window !== 'undefined' && typeof window.localStorage !== 'undefined') {
return window.localStorage;
}
} catch {
return null;
}
return null;
}
private getBearerToken(): string | null {
const storage = this.getStorage();
if (storage === null) {
return null;
}
return this.normalizeBearerToken(storage.getItem(this.bearerStorageKey));
}
private getRequestHeaders(headers: APIliteRequestHeaders = {}): APIliteRequestHeaders {
const requestHeaders: APIliteRequestHeaders = { ...headers };
if (typeof requestHeaders.Authorization === 'undefined') {
const token = this.getBearerToken();
if (token !== null) {
requestHeaders.Authorization = `Bearer ${token}`;
}
}
return requestHeaders;
}
private applyHeaders(xhttp: XMLHttpRequest, headers: APIliteRequestHeaders): void {
Object.keys(headers).forEach((key) => {
const value = headers[key];
if (typeof value === 'undefined' || value === null) {
return;
}
xhttp.setRequestHeader(key, value);
});
}
bearerSet(token: string | null): void {
const storage = this.getStorage();
if (storage === null) {
return;
}
const normalizedToken = this.normalizeBearerToken(token);
if (normalizedToken === null) {
storage.removeItem(this.bearerStorageKey);
return;
}
storage.setItem(this.bearerStorageKey, normalizedToken);
}
private call(
method: string,
@ -161,6 +225,7 @@ class <?php echo $this->apiName; ?> {
callback: (response: APIliteHelpResponse | APIliteActionResponse<unknown> | APIliteErrorResponse) => void
): void {
const xhttp = new XMLHttpRequest();
const headers = this.getRequestHeaders();
xhttp.withCredentials = true;
xhttp.onreadystatechange = function() {
if (this.readyState === 4) {
@ -191,6 +256,7 @@ class <?php echo $this->apiName; ?> {
});
xhttp.open('POST', this.endpoint + '?action=' + method);
this.applyHeaders(xhttp, headers);
xhttp.send(formData);
}
@ -231,4 +297,4 @@ class <?php echo $this->apiName; ?> {
<?php } ?>
}
export default new <?php echo $this->apiName; ?>();
export default new <?php echo $this->apiName; ?>();