added into generated client response handlers

This commit is contained in:
2026-05-26 13:45:15 +02:00
parent 808fd747fe
commit 88bf5a84d8
4 changed files with 135 additions and 8 deletions

View File

@ -8,6 +8,8 @@
class <?php echo $this->apiName; ?> {
endpoint = <?php echo sprintf(substr($this->endpoint, 0, 4) == 'http' ? '"%s"' : '%s', $this->endpoint); ?>;
bearerStorageKey = 'apilite_bearer_token';
responseHandlers = [];
errorHandlers = [];
normalizeBearerToken(token) {
if (typeof token !== 'string') return null;
@ -58,20 +60,64 @@ class <?php echo $this->apiName; ?> {
storage.setItem(this.bearerStorageKey, token);
}
addResponseHandler(handler) {
this.responseHandlers.push(handler);
return () => {
this.responseHandlers = this.responseHandlers.filter(registeredHandler => registeredHandler !== handler);
};
}
addErrorHandler(handler) {
this.errorHandlers.push(handler);
return () => {
this.errorHandlers = this.errorHandlers.filter(registeredHandler => registeredHandler !== handler);
};
}
emitResponseHandlers(response, context) {
this.responseHandlers.forEach(handler => {
try {
handler(response, context);
} catch (error) {
// Response handlers must not change the API request result.
}
});
}
emitErrorHandlers(response, context) {
this.errorHandlers.forEach(handler => {
try {
handler(response, context);
} catch (error) {
// Error handlers must not change the API request result.
}
});
}
emitHandlers(response, context) {
this.emitResponseHandlers(response, context);
if (response.status === 'ERROR') this.emitErrorHandlers(response, context);
}
/* ----------------------------------------------------
* General API call
*/
call(method, data, callback) {
var xhttp = new XMLHttpRequest();
var headers = this.getRequestHeaders();
var api = this;
xhttp.withCredentials = true;
xhttp.onreadystatechange = function() {
if (this.readyState === 4) {
var response;
if (this.status === 200) {
if (callback != null) callback(JSON.parse(this.responseText));
response = JSON.parse(this.responseText);
} else {
if (callback != null) callback({'status': 'ERROR', 'msg': 'HTTP STATUS ' + this.status});
response = {'status': 'ERROR', 'msg': 'HTTP STATUS ' + this.status};
}
var context = {method: method, data: data, httpStatus: this.status};
api.emitHandlers(response, context);
if (callback != null) callback(response);
}
}
var form_data = new FormData();
@ -118,4 +164,4 @@ class <?php echo $this->apiName; ?> {
};
export default new <?php echo $this->apiName; ?>();
export default new <?php echo $this->apiName; ?>();